We already use lists!
for i in [5, 4, 3, 2, 1] :
print i
print 'Blastoff!'
5
4
3
2
1
Blastoff!
Lists and definite loops - best pals
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy New Year:', friend
print 'Done!'
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
Done!
Looking Inside Lists
•
Just like strings, we can get at any single element in a list using an index
specified in square brackets
0
Joseph
>>> friends = [ 'Joseph', 'Glenn', 'Sally' ]
>>> print friends[1]
Glenn
>>>
1
Glenn
2
Sally
Lists are Mutable
•
Strings are "immutable" - we
cannot change the contents of
a string - we must make a
new string to make any
change
•
Lists are "mutable" - we can
change an element of a list
using the index operator
>>> fruit = 'Bannna'
>>> fruit[0] = 'b'
Traceback
TypeError: 'str' object does not
support item assignment
>>> x = fruit.lower()
>>> print x
bannna
>>> lotto = [2, 14, 26, 41, 63]
>>> print lotto
[2, 14, 26, 41, 63]
>>> lotto[2] = 28
>>> print lotto
[2, 14, 28, 41, 63]
How Long is a List?
•
The len() function takes a list as a
parameter and returns the
number of elements in the list
•
Actually len() tells us the number
of elements of any set or sequence
(i.e. such as a string )
>>> greet = 'Hello Bob'
>>> print len(greet)
9
>>> x = [ 1, 2, 'joe', 99]
>>> print len(x)
4
>>>
Using the range function
•
The range function returns a list
of numbers that range from zero
to one less than the parameter
•
We can construct an index loop
using for and an integer iterator
>>> print range(4)
[0, 1, 2, 3]
>>> friends = ['Joseph', 'Glenn', 'Sally']
>>> print len(friends)
3
>>> print range(len(friends))
[0, 1, 2]
>>>
A tale of two loops
friends = ['Joseph', 'Glenn', 'Sally']
for friend in friends :
print 'Happy New Year:', friend
for i in range(len(friends)) :
print 'Happy New Year:', friends[i]
Happy New Year: Joseph
Happy New Year: Glenn
Happy New Year: Sally
>>> friends = ['Joseph', 'Glenn', 'Sally']
>>> print len(friends)
3
>>> print range(len(friends))
[0, 1, 2]
>>>
Concatenating lists using +
•
We can create a new list by adding
two exsiting lists together
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
>>> print a
[1, 2, 3]
Lists can be sliced using :
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
Remember: Just like in
strings, the second number
is "up to but not
including"
List Methods
>>> x = list()
>>> type(x)
<type 'list'>
>>> dir(x)
['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>>
http://docs.python.org/tutorial/datastructures.html
Không có nhận xét nào:
Đăng nhận xét