1 遍历整个列表
假设我们有一个魔术师名单,下面使用for循环来打印魔术师名单中的所有名字:
#magicians.py
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
输出:
alice
david
carolina
1.1
编写for循环时,对于用于存储列表中每个值的临时变量,可指定任何名称。然而,选择描述单个列表元素的有意义的名称大有帮助。例如,对于小猫列表、小狗列表和一般性列表,像下面这样编写for循环的第一行代码是不错的选择:
for cat in cats:
for dog in dogs:
for item in list_of_items:
这些命名约定有助于你明白for循环中将对每个元素执行的操作。使用单数和复数式名称,可帮助你判断代码段处理的是单个列表元素还是整个列表。
1.2 在for循环中执行更多的操作
下面来扩展前面的示例,对于每位魔术师,都打印一条消息,指出他的表演太精彩了。
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick! ")
输出:
Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
在for循环中,想包含多少行代码都可以。在代码行for magician in magicians后面,每个缩进的代码行都是循环的一部分,且将针对列表中的每个值都执行一次。因此,可对列表中的每个值执行任意次数的操作。
下面再添加一行代码,告诉每位魔术师,我们期待他的下一次表演:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician.title() + ", that was a great trick! ")
print("I can't wait to see your next trick, " + magician.title() + ".\n")
输出:
Alice, that was a great trick!
I can't wait to see your next trick, Alice.
David, that was a great trick!
I can't wait to see your next trick, David.
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.
1.3 在for循环结束后执行一些操作