大家好,小编为大家解答python列表的基本操作编程的问题。很多人还不知道关于python列表的题,现在让我们一起来看看吧!
4.1 遍历整个列表
需要对列表的每个元素都执行相同的操作时,可使用Python中的for循环。示例如下:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
执行结果:
4.1.1 深入了解循环
循环是让计算机自动完成重复工作的方式之一用python画雪人。
编写for循环时,可以依次给与列表中的每个值有关的临时变量任意名称。
4.1.2 在for循环中执行更多操作
在for循环中,可对每个元素执行任何操作。代码示例如下:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f'{magician.title()},that was a great trick!')
执行结果:
在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")
执行结果:
4.1.3 在for循环结束后执行一些操作
在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("Think you,everyone.That was a great magic show!")
执行结果
4.2 避免缩进错误
Python根据缩进来判断代码行与前一个代码行的关系。因此需要注意一些常见的缩进错误。
4.2.1 忘记缩进
对于位于for语句后面且属于循环组成部分的代码行,一定要缩进。错误代码示例:
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(message)
执行结果:
只需要在print语言中进行缩进即可。
4.2.2 忘记缩进
有时候,循环能够运行且不会报告错误,但结果可能出乎意料。
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")
执行结果:
预期是每人都收到一句wait to see your next trick,但结果只有Carolina收到。而这就是一种逻辑错误,导致结果不符合预期。
4.2.3 不必要的缩进
如果不小心缩进了无须缩进的代码行,也会报错:
magicians = ['alice', 'david', 'carolina']
print(magicians)
执行结果:
4.2.4 循环后的不必要缩进
如果循环了应在循环后执行的代码,这些代码将会重复执行。这种情况可能会导致语法错误,但是大多数情况是逻辑错误:
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("Think you,everyone.That was a great magic show!")
执行结果:
4.2.5 遗漏了冒号
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("Think you,everyone.That was a great magic show!")
执行结果:
4.2.6 练习
练习 4-1: 披萨 想出至少三个喜欢的披萨,并将其保存在列表当中,在使用for循环将每种披萨打印出来。
· 修改这个for循环,士气每一列都打印一个句子。
· 在末尾添加一句代码,不在循环内。
代码示例:
pizzas = ['durian pizza', 'beef pizza', 'pineapple and shrime pizza']
for pizza in pizzas:
print(f'I like {pizza}!')
print(f'I really love pizza!')
执行结果:
练习 4-2:动物 想出至少3中共同特征的动物,将其名称存储在一个列表当中,再用for循环打印出来:
· 修改这个成勋,使每个动物都打印一个句子。
· 在末尾加一句代码,指出这些动物的共同之处。
代码示例:
animals = ['tigers', 'lions', 'leopards']
for animal in animals:
print(f'A {animal} would make a great wild animal!')
print(f"They are all felid!")
执行结果:
4.3 创建数据列表
列表适合用于存储数据的组合,因此python有很多工具用于处理数字类型的列表。
4.3.1 使用range()函数
Python的range()函数可以生成一系列数。代码示例如下:
for value in range(1,5):
print(value)
执行结果:
函数range()让Python从指定的第一个值开始数,并达到第二个值开始停止。因此不包含第二个值。
若使用range()函数时,不符号预期结果,可以将指定的值加一或者减一。
调用range()函数时,也可以指定一个参数,则默认从0开始取值。
4.3.2 使用range()函数创建数字列表
要使用range()函数创建数字列表,可以同时使用list(),range()函数即可创建数字列表。代码示例如下:
numbers = list(range(1,6))
print(numbers)
执行结果:
使用range()还可以指定步长。代码示例:
even_numbers = list(range(2, 11, 2))
print(even_numbers)
执行结果:
使用range()几乎能够创建任何需要的数集。代码示例如下:
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)
执行结果:
为了使代码更简洁,可以不使用临时变量square,直接附加到表中。
squares = []
for value in range(1, 11):
squares.append(value ** 2)
print(squares)
执行结果:
4.3.3 对数字列表执行简单的统计计算
Python用于处理数字列表的函数。求最大值,最小值,求和,代码示例如下:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('最小值:{}'.format(min(digits)))
print('最大值:{}'.format(max(digits)))
print('求和:{}'.format(sum(digits)))
执行结果:
4.3.4 列表解析
列表解析是将for循环和创建元素代码合并到一行,并自动附加新元素。代码示例如下:
squares = [value ** 2 for value in range(1, 11)]
print(squares)
执行结果:
4.3.5 练习
练习 4-3:数到20 使用一个for循环打印1~20包括20
代码示例:
counts = [value for value in range(1,21)]
print(counts)
执行结果:
练习 4-4:一百万 创建一个包含1~10000000的列表,在使用for循环打印出来
代码示例:
counts = [value for value in range(1, 1000001)]
for count in counts:
print(count)
执行结果:
练习 4-5:一百万求和 在4-4基础上,使用min()和max()核实列表的最大值和最小值,和进行sum()求和。
代码示例:
counts = [value for value in range(1, 1000001)]
print(f"初始值:{min(counts)}")
print(f"最终值:{max(counts)}")
print(f"和:{sum(counts)}")
执行结果:
练习 4-6:奇数 通过range()函数创建一个列表,包含1~20的奇数,并用for循环打印出来
代码示例:
counts = [value for value in range(1, 21, 2)]
for count in counts:
print(count)
执行结果:
练习 4-7:3的倍数 创建一个列表,其中包含3~30能被3整除的数,再使用for循环打印出来。
代码示例:
counts = [value * 3 for value in range(1, 11)]
for count in counts:
print(count)
执行结果:
4.4 使用列表的一部分
处理列表的部分元素,在Python中称为切片。
4.4.1 切片
创建切片,可以指定第一个和最后一个元素的索引(不包括最后一个元素)。代码示例如下:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
执行结果:
通过切片可以生成任意子集,如果没有指定第一个索引,将默认从0开始。代码示例如下:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
执行结果:
4.4.2 遍历切片
如果要遍历列表的部分元素,可以在for循环内使用切片,代码示例如下:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print('Here are the first three players on my team:')
for player in players[:3]:
print(player)
执行结果:
4.4.3 复制列表
要复制列表,可以创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。代码示例如下:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print("My favorite foods are:")
print(my_foods)
print("My friend foods favorite foods are:")
print(friend_foods)
执行结果:
为核实是两个列表,可分别给两个列表添加一个不同的元素,并打印出来,代码示例如下:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('coffe')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("My friend foods favorite foods are:")
print(friend_foods)
执行结果:
在不是用切片的情况下复制列表如下代码所示:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
my_foods.append('coffe')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("My friend foods favorite foods are:")
print(friend_foods)
执行结果可以看出输出列表是完全相同的:
4.4.4 练习
练习 4-10:切片 选择本章任意程序,在末尾添加以下代码:
· 打印消息“The first three items in the list are:”,打印列表前三个元素
· 打印消息“Three items from the middle of the list are:”,在打印列表中间三个元素
· 打印消息“The last three items in the lisrt are:”,打印列表最后三个元素
代码示例如下:
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("The first three items in the list are:")
for value in players[:3]:
print(value)
print("Three items from the middle of the list are:")
for value in players[1:4]:
print(value)
print("The last three items in the lisrt are:")
for value in players[2:]:
print(value)
执行结果:
练习 4-11:你的披萨,我的披萨 在4-1的基础上,常见一个副本并赋值给friend_pizzas,再完成以下任务:
· 在原列表加上一种元素
· 在friend_pizzas加一种披萨
· 核实两个列表,打印消息“My favorite pizzes are:”,再使用一个for循环打印第一个列表,打印消息“My friend's favorite pizzes are:”,再使用一个for循环打印第一个列表
代码示例如下:
pizzas = ['durian pizza', 'beef pizza', 'pineapple and shrime pizza']
friend_pizzas = pizzas[:]
pizzas.append("big pizza")
friend_pizzas.append("small pizza")
print("My favorite pizzes are:")
print(pizzas)
print("My friend's favorite pizzes are:")
print(friend_pizzas)
执行结果:
练习 4-12:使用多个循环 在foods基础上使用两个循环将食品列表打印出来。
代码示例如下:
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
my_foods.append('coffe')
friend_foods.append('ice cream')
print("My favorite foods are:")
for value in my_foods:
print(value)
print("My friend foods favorite foods are:")
for value in friend_foods:
print(value)
执行结果:
4.5 元组
Python中将不能修改的元素成为不可变的,不可变的列表称为元组
4.5.1 定义元组
元组是用圆括号来进行表示,可以通过索引来访问元组:
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
执行结果:
4.5.2 遍历元组所有元素
可以使用for循环遍历元组所有元素,代码如下:
dimensions = (200, 50)
for value in dimensions:
print(value)
执行结果:
4.5.3 修改元组元素
虽然不能修改元组的元素,但是可以给存储元组的变量赋值。代码示例如下:
dimensions = (200, 50)
print("Original dimensions:")
for value in dimensions:
print(value)
dimensions = (400, 100)
print("\nModified dimensions:")
for value in dimensions:
print(value)
执行结果:
4.5.4 练习
练习 4-13:自助餐 有一家自助参观,只提供5种菜品。请想出常见的五种菜品,并存储在一个元组当中:
· 使用一个for循环打印所有菜品
· 尝试修改一个菜品看python的反应
· 替换两个菜品,重新给元组赋值
代码示例如下:
foods = ('pizza', 'falafel', 'carrot cake', "beef", "banana")
print("Buffet dishes are as follows:")
for value in foods:
print(value)
print("\nModify two kinds of food:")
foods = ('pizza', 'apple', 'milk', "beef", "banana")
for value in foods:
print(value)
print("\nAttempt to modify:")
foods[2] = "apple"
执行结果: