>>> for magician in magicians:
... print(magician)
...
alice
david
carolina
首先,程序执行第一行代码,获取列表magcians中的第一个值,将其存储到变量magician中。
for magician in magicians:
读取下一行代码:
print(magician)
让Python打印magician的值,由于列表中还有其他值,Python返回到循环的第一行:
for magician in magicians:
接下来继续打印列表中的其他元素,知道列表中没有剩余元素。
在for循环中,可对每一个元素进行操作:
>>> for magician in magicians:
... print(magician.title()+",Hello!")
...
Alice,Hello!
David,Hello!
Carolina,Hello!
for name in names:
print(name)
print("It's over")
longxiaoling
chenmingqin
fengsiming
It's over
注意不要将不必要缩进的代码块缩进,而对于必须缩进的代码块却忘了缩进。
for name in names:
print(name)
print(name)
^
IndentationError: expected an indented block
for name in names
^
SyntaxError: invalid syntax
>>> for val in range(1,5):
... print(val)
...
1
2
3
4
>>> arr = list(range(5))
>>> print(arr)
[0, 1, 2, 3, 4]
range()
函数可以指定步长
>>> arr = list(range(1,9,2))
>>> arr
[1, 3, 5, 7]
>>> min(arr)
1
>>> max(arr)
7
>>> sum(arr)
16
使用列表解析式创建1~9的平方数
>>> square = [val**2 for val in range(10)]
>>> square
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> players = ['charles','martina','michael','florence','ali']
>>> players[:3]
['charles', 'martina', 'michael']
负数索引返回离列表末尾相应距离的元素,例如,如果你想要输出名单上的最后三名队员,可使用以下代码:
>>> players[-3:]
['michael', 'florence', 'ali']
只遍历列表前三名队员:
>>> for name in players[:3]:
... print(name)
...
charles
martina
michael
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:]
)。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
>>> my_foods = ['pizza','falafel','carrot cake']
>>> friend_foods= my_foods[:]
>>> my_foods
['pizza', 'falafel', 'carrot cake']
>>> friend_foods
['pizza', 'falafel', 'carrot cake']
核实我们确实有两个列表:
>>> my_foods.append('cannoli')
>>> friend_foods.append('ice cream')
>>> my_foods
['pizza', 'falafel', 'carrot cake', 'cannoli']
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'ice cream']
如果不使用切片复制列表,则是将两个变量同时指向一个列表:
>>> friend_foods = my_foods
>>> my_foods.append('cannoli')
>>> friend_foods.append('ice cream')
>>> my_foods
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'cannoli', 'cannoli', 'ice cream']
如果需要创建一系列不可修改的元素,元组可以满足这种需求。不可变的列表称之为元组。
使用圆括号
来标识元组。
>>> dimension = (200,50)
>>> dimension
(200, 50)
>>> dimension[0]
200
修改元组的操作是被禁止的,因此Python指出不能给元组的元素幅值:
>>> dimension[0] = 10
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> for dim in dimension:
... print(dim)
...
200
50
虽然不能修改元组的元素,但可以给存储元组的变量重新赋值,重新定义整个元组:
>>> dimension = (20,30)
>>> dimension
(20, 30)