操作列表
遍历整个列表,无论列表有多长,循环让列表中的每一个元素都采取一个或一系列相同的措施,从而高效地处理任何长度的列表,包含数以千至数百万个元素的列表。
遍历整个列表
通过for循环解决遍历
从列表中取出一个元素放入新的变量中,最后打印新的变量,最后重复执行这两步
# 遍历整个列表案例
magicians = ['alice','david','carolina']
# 从列表中取出一个元素放入新的变量中,最后打印新的变量
for magician in magicians:
print(magician)
alice
david
carolina
深入地研究循环
循环是计算机自动完成重复工作的常见方式之一。
对列表中的每个元素,都将执行循环指定的步骤,而不管列表包含多少个元素。如果列表包含一百万个元素, Python 就重复执行指定的步骤一百万次,且通常速度非常快。
编写 for 循环时,对于用于存储列表中每个值的临时变量,可指定任何名称。然而,选择描述单个列表元素的有意义的名称大有帮助。
# 临时变量名称案例
for cat in cats:
for dog in dogs:
for item in list_of_items:
在for循环中执行更多的操作
for循环中,可以对每个元素执行任何操作
# for循环执行操作案例
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.
在for循环结束后执行一些操作
在 for 循环后面,没有缩进的代码都只执行一次,而不会重复执行。
# for循环结束后执行案例
magicians = ['alice','david','carlolina']
for magician in magicians:
print(magician.title() + ", that was a great trick!")
print("I can't wait to see you next trick, " + magician.title() + ".\n")
print("Thank you, enveryone. That was a great magic show!")
Alice, that was a great trick!
I can't wait to see you next trick, Alice.
David, that was a great trick!
I can't wait to see you next trick, David.
Carlolina, that was a great trick!
I can't wait to see you next trick, Carlolina.
Thank you, enveryone. That was a great magic show!
练习
# 1.比萨
# 想出至少三种喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称都打印出来
# 修改这个for循环,使其打印包含比萨名称的句子,对于每种比萨都显示一行输出,如“I like pizza”
# 在程序末尾添加一行代码,不在for循环里,指出你有多喜欢比萨,输出应包含对每种比萨的消息,还有一个总结性句子,如“I reall love pizza”
pizzas = ['chess pizza','beef pizza','corn pizza','pepperoni pizza']
for pizza in pizzas:
print(pizza)
print("#" * 20)
for pizza in pizzas:
print("I like " + pizza.title() + "!")
print("\nI reall love pizza!")
chess pizza
beef pizza
corn pizza
pepperoni pizza
####################
I like Chess Pizza!
I like Beef Pizza!
I like Corn Pizza!
I like Pepperoni Pizza!
I reall love pizza!
# 2.动物
# 想出至少3种有共同特征的动物,将这些动物的名称存储在一个列表中,再使用for循环将每种动物的名称都打印出来
# 修改这个程序,使每种动物都打印一个句子,如“A dog would make a great pet”。
# 在程序末尾添加一行代码,指出这些动物的共同之处,如:“Any of these animals would make a great pet!”
animals = ['goat','sheep','lamb']
for animal in animals:
print(animal)
print("A " + animal.title() + " would make a great pet.")
print("\nAny of these animals would make a great pet!")
goat
A Goat would make a great pet.
sheep
A Sheep would make a great pet.
lamb
A Lamb would make a great pet.
Any of these animals would make a great pet!