Python编程从入门到实践(三)-操作列表

本文介绍了Python中操作列表的方法,包括遍历列表、在for循环中执行多个操作、在循环结束后执行操作、使用range()创建数字列表并进行统计计算、列表解析、处理列表切片以及元组的定义和使用。通过实例展示了如何遍历列表、创建数字列表、获取列表的统计信息、以及如何使用切片和元组来存储和操作数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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循环结束后执行一些操作

下面来打印一条向全体魔术师致谢的消息,感谢他们的精彩表演。想要在打印给各位魔术师的消息后面打印一条给全体魔术师的致谢消息,需要将相应的代码放在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")
print("Thank you, everyone. That was a great magic show! ")

输出:
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.
Thank you, everyone. That was a great magic show!

3 创建数值列表
3.1 使用函数range()
Python函数range()能够轻松地生成一系列的数字。:

#numbers.py
for value in range(1,5):
    print(value)

上述代码好像应该打印数字1~5,但实际上它不会打印数字5:
1
2
3
4

函数range()让Python从你指定的第一个值开始数,并在到达你指定的第二个值后停止,因此输出不包含第二个值。
3.2 使用range()创建数字列表
要创建数字列表,可使用函数list()将range()的结果直接转换为列表将range()作为list()的参数,输出将为一个数字列表

numbers = list(range(1,6))
print(numbers)

结果如下:
[1, 2, 3, 4, 5]
使用函数range()时,还可指定步长。例如,下面的代码打印1~10内的偶数:

#even_numbers.py
even_numbers = list(range(2,11,2))
print(even_numbers)

在这个示例中,函数range()从2开始数,然后不断地加2,直到达到或超过终值(11),输出如下:
[2, 4, 6, 8, 10]
使用函数range()几乎能够创建任何需要的数字集,下面的代码演示了如何将前10个整数的平方加入到一个列表中:

#squares.py
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]
为让这些代码更简洁,可不使用临时变量square,而直接将每个计算得到的值附加到列表末尾:  

squares = []
for value in range(1,11):
    squares.append(value**2)
print(squares)

3.3 对数字列表执行简单的统计计算
最大值、最小值和总和:

digits=[1,2,3,4,5,6,7,8,9,0]
print(min(digits))
print(max(digits))
print(sum(digits))

输出:

0

9

45
3.4 列表解析
列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。

#squares.py
squares = [value**2 for value in range(1,11)]
print(squares)

定义一个描述性的列表:squares;然后,指定一个左方括号,并定义一个表达式,用于生成你要存储到列表中的值。在这个示例中,表达式为value**2,它计算平方值。接下来,编写一个for循环,用于给表达式提供值,再加上右方括号。在这个示例中,for循环为for value in range(1,11),它将值1~10提供给表达式value**2。请注意,这里的for语句末尾没有冒号
结果与你在前面看到的平方数列表相同:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4 使用列表的一部分
你还可以处理列表的部分元素——Python称之为切片。
4.1 切片
要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,Python在到达你指定的第二个索引前面的元素后停止。要输出列表中的前三个元素,需要指定索引0~3,这将输出分别为0、1和2的元素。
下面的示例处理的是一个运动队成员列表:

#players.py
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])

输出:
['charles', 'martina', 'michael']
你可以生成列表的任何子集,例如,如果你要提取列表的第2~4个元素,可将起始索引指定为1,并将终止索引指定为4:

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4])

输出:
['martina', 'michael', 'florence']
如果你没有指定第一个索引,Python将自动从列表开头开始

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])

输出:
['charles', 'martina', 'michael', 'florence']

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])

Python将返回从第3个元素到列表末尾的所有元素:
['michael', 'florence', 'eli']

负数索引返回离列表末尾相应距离的元素,因此你可以输出列表末尾的任何切片。如果你要输出名单上的最后三名队员,可使用切片players[-3:]:

players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])

4.2 遍历切片
在下面的示例中,我们遍历前三名队员,并打印他们的名字:  

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
4.3 复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
例如,假设有一个列表,其中包含你最喜欢的三种食品,而你还想创建另一个列表,在其中包含一位朋友喜欢的所有食品。不过,你喜欢的食品,这位朋友都喜欢,因此你可以通过复制来创建这个列表:

#foods.py
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']

5 元组

Python将不能修改的值称为不可变的,而不可变的列表被称为元组
5.1 定义元组
元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。
例,如果有一个大小不应改变的矩形,可将其长度和宽度存储在一个元组中,从而确保它们是不能修改的:

#dimensions.py
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])

输出:
200
50
如果修改元组dimensions中的一个元素则:

dimensions = (200, 50)
dimensions[0] = 250


5.2 遍历元组中的所有值

dimensions = (200, 50)
for dimension in dimensions:
    print(dimension)

输出:
200
50
5.3 修改元组变量
如果要修改前述矩形的尺寸,可重新定义整个元组:

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
相比于列表,元组是更简单的数据结构。如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。

6 代码格式
PEP 8

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值