第4章 操作列表

4.1 遍历整个列表

你经常需要遍历列表的所有元素,对每个元素执行相同的操作。通过使用for循环,可让Python去处理这些问题。

下面使用for循环来打印魔术师名单中的所有名字:

# for循环打印列表中的所有元素
magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician)

# 输出
alice
david
carolina

4.1.1深入研究循环

循环这种概念很重要,因为它是让计算机自动完成重复工作的常见方式之一。

1.对列表中的每个元素,都将执行循环指定的步骤,不管列表包含多少个元素。
2.编写for循环时,对于用于存储列表中每个值的临时变量,可指定任何名称。

4.1.2 在for循环中执行更多的操作

在for循环中,可对每个元素执行任何操作。

# 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循环结束后执行操作
magicians = ['alice','david','carolina']
for magician in magicians:
    print(magician.title()+",that was a great trick!")
print("Thank you,everyone.")

# 输出
Alice,that was a great trick!
David,that was a great trick!
Carolina,that was a great trick!
Thank you,everyone.

4.2 避免缩进错误

1.Python根据缩进来判断代码行与前一个代码行的关系。
2.Python通过使用缩进让代码更易读。

4.3创建数值列表

列表非常适合用于存储数字集合。

4.3.1 使用函数range()

Python函数range()让你能够轻松的生成一系列的数字。

# 创建数值列表
for value in range(1,5):
	print(value)

# 输出
1
2
3
4

# 说明:在这个示例中,只打印了1~4,函数range()让Python从指定的第一个值开始,并到达指定的第二个值,不包含第二个值

4.3.2 使用range()创建数字列表

要创建数字列表,可使用函数list()将range()的结果直接转换为列表。

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

# 输出
[1, 2, 3, 4, 5]

# 说明:range(1,6)默认是步长为1,即从1开始每次加1。

使用函数range()时,还可以指定步长,如下面,打印1~10内的偶数:

# 打印1~10内的偶数
numbers = list(range(2,11,2))
print(numbers)

# 输出
[2, 4, 6, 8, 10]

# 说明:range(2,11,2)默认是步长为2,即从2开始每次加2。

创建一个列表,其中包含整数1~10的平方:

# 创建一个列表,其中包含整数1~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]

4.3.3 对数字列表执行简单的统计计算

1.统计列表中的最小值、最大值、求和。

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

# 输出
0
9
45

4.3.4 列表解析

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

下面示例使用列表解析创建平方数列表:

# 1~10的平方列表
squares = [value**2 for value in range(1,11)]
print(squares)

# 输出
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4.4 使用列表的一部分

你还可以处理列表的部分元素——Python称之为切片

4.4.1 切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。与函数range()一样,Python在到达指定的第二个索引后停止。要输出列表中的前三个元素,需要指定索引0~3。

1.指定起始和终止索引,处理一个成员列表:

# 打印前三个元素
players = ['charles','martina','michael','florence','eli']
print(players[0:3])

# 输出
['charles', 'martina', 'michael']

# 说明1:切片输出的也是一个列表

2.没有指定起始索引:

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

# 输出
['charles', 'martina', 'michael']

# 说明:没有指定起始索引,Python从列表开头开始提取

3.没有指定终止索引:

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

# 输出
['michael', 'florence', 'eli']

# 说明:没有指定终止索引,Python从列表索引开始提取到末尾

4.返回列表后3个元素:

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

# 输出
['michael', 'florence', 'eli']

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.title())

# 输出
Here are the first three players on my team:
Charles
Martina
Michael

4.4.3 复制列表

你经常需要根据既有列表创建全新的列表。下面来介绍复制列表的工作原理,以及复制列表可提供极大帮助的一种情形。

要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])。这让Python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

1.使用切片复制列表

my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods[:]
print(friend_foods)

# 输出
['pizza', 'falafel', 'carrot cake']

# 说明:在不指定任何索引的情况下从列表my_foods中提取一个切片,从而创建了这个列表的副本,再将该副本存储到变量friend_foods中。

2.不使用切片复制列表

# 不使用切片复制列表                                 
my_foods = ['pizza','falafel','carrot cake']
friend_foods = my_foods                     
my_foods.append('cannoli')                  
print(my_foods)                             
print(friend_foods)

# 输出
['pizza', 'falafel', 'carrot cake']       
['pizza', 'falafel', 'carrot cake']

# 说明:这里将my_foods赋值给friend_foods,两个变量都指向同一个列表。                  

4.5 元组

列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可以修改的,然而,有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。

Python将不能修改的值称为不可变的,而不变的列表被称为元组。

4.5.1 定义元组

元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后就可以使用索引来访问其元素,就像访问列表元素一样。

1.定义一个元组,并打印各个元素

# 定义一个元组
dimensions = (200,50)
print(dimensions[0])
print(dimensions[1])

# 输出
200
50

2.修改元组的一个元素,结果是被禁止的

# 修改元组的元素值
dimensions = (200,50)
dimensions[0] = 250

# 输出
Traceback (most recent call last):
  File "<input>", line 3, in <module>
TypeError: 'tuple' object does not support item assignment

4.5.2 遍历元组中的所有值

像列表一样,也可以使用for循环来遍历元组中的所有值:

# 遍历元组中的所有值
dimensions = (200,50)
for dimension in dimensions:
	print(dimension)

# 输出
200
50

4.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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值