目录
4.1 遍历整个列表
4.1.1 深入研究循环
4.1.2 在for 循环中执行更多操作
4.1.3 在for 循环结束后执行一些操作
4.2 避免缩进错误
4.2.1 忘记缩进
4.2.2 忘记缩进额外的代码行
4.2.3 不必要的缩进
4.2.4 循环后不必要的缩进
4.2.5 遗漏了冒号
4.2.6 练习
练习4-1:比萨
练习4-2:动物
4.3 创建数值列表
4.3.1 使用函数range()
4.3.2 使用range() 创建数字列表
4.3.3 对数字列表执行简单的统计计算
4.3.4 列表解析
4.3.5 练习
练习4-3:数到20
练习4-4:一百万
练习4-5:一百万求和
练习4-6:奇数
练习4-7:3的倍数
练习4-8:立方
练习4-9:立方解析
4.4 使用列表的一部分
4.4.1 切片
4.4.2 遍历切片
4.4.3 复制列表
4.4.4 练习
练习4-10:切片
练习4-11:你的比萨,我的比萨
练习4-12:使用多个循环
4.5 元组
4.5.1 定义元组
4.5.2 遍历元组中的所有值
4.5.3 修改元组变量
4.5.4 练习
练习4-13:自助餐
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
alice
david
carolina
for magician in magicians:
print(magician)
for magician in magicians:
print(magician)
for cat in cats:
for dog in dogs:
for item in list_of_items:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print((f"{magician.title()}, that was a great trick!"))
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print((f"{magician.title()}, that was a great trick!"))
print(f"I can't wait to see your next trick, {magician.title()}.\n")
在 for 循环中,想包含多少行代码都可以。
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print((f"{magician.title()}, that was a great trick!"))
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")
pizzas = ['seafood', 'sausage', 'cheese']
for pizza in pizzas:
print(f"I like {pizza} pizza")
print("I really like pizza!")
animals = ['dog', 'cat', 'rabbit']
for animal in animals:
print(f"A {animal} would make a great pet")
print("Any of these animals would make a great pet!")
for value in range(1, 5):
print(value)
1
2
3
4
for value in range(1, 6):
print(value)
调用函数 range() 时,也可只指定一个参数,这样它将从0开始。例如,range(6) 返回数0~5。
numbers = list(range(1, 6))
print(numbers)
[1, 2, 3, 4, 5]
even_numbers = list(range(2, 11, 2))
print(even_numbers)
[2, 4, 6, 8, 10]
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> digits = [1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
squares = [value**2 for value in range(1, 11)]
print(squares)
numbers = [value for value in range(1, 21)]
for number in numbers:
print(number)
numbers = [value for value in range(1, 1000001)]
for number in numbers:
print(number)
numbers = [value for value in range(1, 1000001)]
print(min(numbers))
print(max(numbers))
print(sum(numbers))
numbers = [value for value in range(1, 20, 2)]
print(numbers)
numbers = []
for value in range(1, 11):
numbers.append(value*3)
for number in numbers:
print(number)
numbers = []
for value in range(1, 11):
numbers.append(value**3)
for number in numbers:
print(number)
numbers = [value**3 for value in range(1, 11)]
print(numbers)
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
['charles', 'martina', 'michael']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])
['martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
['charles', 'martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])
['michael', 'florence', 'eli']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])
注意 可在表示切片的方括号内指定第三个值。这个值告诉Python在指定范围内每隔多少元素提取一个。
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
for player in players[:3]:
print(player.title())
Here are the first three players on my team:
Charles
Martina
Michael
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake']
my_foods = ['pizza', 'falafel', 'carrot cake']
# 这行不通:
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)
My favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
My friend's favorite foods are:
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
注意 暂时不要考虑这个示例中的细节。当试图使用列表的副本时结果出乎意料,基本上都要确认你是否像第一个示例那样使用切片复制了列表。
my_foods = ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print("The first three items in the list are:")
for food in my_foods[:3]:
print(food)
print("\nThree items from the middle of the list are:")
for food in my_foods[1:4]:
print(food)
print("\nThe last three items in the list are:")
for food in my_foods[-3:]:
print(food)
pizzas = ['seafood', 'sausage', 'cheese']
friend_pizzas = pizzas[:]
pizzas.append("hotdog")
friend_pizzas.append("vegetable")
print("my favorite pizzas are:")
for pizza in pizzas:
print(pizza)
print("my friend favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza)
my_foods = ['pizza', 'falafel', 'carrot cake']
# 这行不通:
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
for my_food in my_foods:
print(my_food)
print("\nMy friend's favorite foods are:")
for friend_food in friend_foods:
print(friend_food)
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
200
50
dimensions = (200, 50)
dimensions[0] = 250
Traceback (most recent call last):
File "dimensions.py", line 2, in
dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment
注意 严格地说,元组是由逗号标识的,圆括号只是让元组看起来更整洁、更清晰。如果你要定义只包含一个元素的元组,必须在这个元素后面加上逗号:my_t = (3,)创建只包含一个元素的元组通常没有意义,但自动生成的元组有可能只有一个元素。
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
200
50
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
Original dimensions:
200
50
Modified dimensions:
400
100
foods = ("tofu", "fish", "meat", "pork", "vegetable")
for food in foods:
print(food)
# 修改菜单
foods = ("tea", "coffee", "meat", "pork", "vegetable")
print("\nAfter editting:")
for food in foods:
print(food)