Learn Python The Hard Way学习(32) - 循环和列表
2012-06-29 08:47:00

hairs = ['brown', 'blond', 'red']
eyes = ['brown', 'blue', 'green']
weights = [1, 2, 3, 4]

list以 [ 号开头，里面的元素以 , 号分隔，像函数的参数一样，然后以 ] 结束，python把所有这些包含在一个变量中。

[python]
the_count = [1, 2, 3, 4, 5]
fruits = ['apples', 'oranges', 'pears', 'apricots']
change = [1, 'pennies', 2, 'domes', 3, 'quarters']

# this first kind of for-loop goes through a list
for number in the_count:
print "This is count %d" % number

# same as above
for fruit in fruits:
print "A fruit of type: %s" % fruit

# also we can go through mixed lists too
# notice we have to use %r since we don't know what's in it
for i in change:
print "I got %r" % i

# we can also build lists, first start with an empty on
elements = []

# then use the range function to do 0 to 5 counts
for i in range(0, 6):
print "Adding %d to the list." % i
# append is a function that lists understand
elements.append(i)

# now we can print them out too
for i in elements:
print "Elements was: %d" % i

root@he-desktop:~/mystuff# python ex32.py
This is count 1
This is count 2
This is count 3
This is count 4
This is count 5
A fruit of type: apples
A fruit of type: oranges
A fruit of type: pears
A fruit of type: apricots
I got 1
I got 'pennies'
I got 2
I got 'domes'
I got 3
I got 'quarters'
Elements was: 0
Elements was: 1
Elements was: 2
Elements was: 3
Elements was: 4
Elements was: 5

1. 弄懂range函数。
range([start], stop[, step])

2. 你能不能不使用22行的for循环，而直接使用range给elemens赋值呢？
elements = range(0, 6)

3. 查看list的帮助文档，看看append附近还有什么函数。