Python编程 从入门到实践——第4章 操作列表

4.1 遍历整个列表

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
	print(magician)

4.1.1 深入研究循环

编写for循环时,可以给依次与列表中每个值相关联的临时变量指定任意名称。

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

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
	print(f"{magician.title()}, that's was a great trick!")
	print(f"I can't wait to see you next trick, {magician.title()}.\n")

在for循环中,想包含多少代码都可以。在代码行for magician in magicians后面,每个缩进的代码行都是循环的一部分。

4.1.3 在for循环结束后执行一些操作

在for循环后面,没有缩进的代码都只执行一次,不会重复执行。

magicians = ['alice', 'david', 'carolina']
for magician in magicians:
	print(f"{magician.title()}, that's was a great trick!")
	print(f"I can't wait to see you next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")

4.2 避免缩进错误

Python根据缩进来判断代码行与前一个代码行的关系。

4.2.1 忘记缩进

4.2.2 忘记缩进额外的代码行

4.2.3 不必要的缩进

4.2.4 循环后不必要的缩进

4.2.5 遗漏了冒号

for语句末尾的冒号告诉Python,下一行是循环的第一行。

4.3 创建数值列表

4.3.1 使用函数range()

Python函数range()让你能够轻松地生成一系列数。函数range()让Python从指定的第一个值开始数,并在到达你指定的第二个值时停止。调用函数range()时,也可指定一个参数,这样它将从0开始。例如,range()返回数0~5。

for value in range(1, 5)print(value)

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

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

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

使用函数range时,还可指定步长。

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

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

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

4.3.4 列表解析

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

squares = [value ** 2 for value in range(1, 11)]  # 这里的for语句没有冒号
print(squares)

4.4 使用列表的一部分

处理列表的部分元素,Python称之为切片。

4.4.1 切片

要创建切片,可指定要使用的第一个元素和最后一个元素的索引。如果没有指定第一个索引,Python将自动从列表开头开始。要让切片终止于列表末尾,也可以使用类似的语法。可在表示切片的方括号内指定第三个值,这个值告诉Python在指定范围内每隔多少元素提取一个。

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

4.4.2 遍历切片

# players.py
players = ['charles', 'martina', 'michael', 'florence', 'eli']

print("Here are the first three players on my team:")
for player in players[:3]print(player.title())

4.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_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_foods = ['pizza', 'falafel', 'carrot cake']
# 这里将my_foods赋给friend_foods,而不是将my_foods的副本赋给friend_foods。
# 这种语法实际上是让Python将新变量friend_foods关联到已与my_foods相关联的列表,因此这两个变量指向同一个列表。
print("another method is wrong")
another_foods = my_foods

print("My favorite foods are:")
print(my_foods)

print("\nMy friend's favorite foods are:")
print(another_foods)

my_foods.append('cannoli')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(another_foods)

another_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(another_foods)

4.5 元组

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

4.5.1 定义元组

元组使用圆括号而非中括号来标识。定义元祖后,就可以使用索引来访问其元素,就像访问列表元素一样。元组是由逗号标识的,圆括号只是让元组看起来更整洁、更清晰。如果你要定义一个只包含一个元素的元组,必须在这个元素后面加上逗号。

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

# 试图修改第一个元素的值,将返回类型错误
dimensions[0] = 250

my_t = (3,)

4.5.2 遍历元组中的所有值

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

4.5.3 修改元组变量

虽然不能修改元组的元素,但可以给存储元组的变量赋值。

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

dimensions = (400, 100)
print("\nModified dimension:")
for dimension in dimensions:
	print(dimension)

4.6 设置代码格式

4.6.1 格式设置指南

Python改进提案(PEP8)

4.6.2 缩进

PEP8建议每级缩进都使用4个空格。如果混合使用了制表符和空格,可将文件中的所有制表符都转换为空格。

4.6.3 行长

建议每行不超过80字符,注释的行长不应超过72字符

4.6.4 空行

要将程序的不同部分分开,可使用空行。

4.6.5 其他格式设置指南

4.7 小结

在本章中,你学习了:如何高效地处理列表中的元素;如何使用for循环遍历列表,Python如何根据缩进来确定程序的结构,以及如何避免一些常见的缩进错误;如何创建简单的数字列表,以及可对数字列表执行的一些操作;如何通过切片来使用列表的一部分和复制列表。你还学习了元组(它对不应变化的值提供了一定程度的保护),以及在代码变得越来越复杂时如何设置格式,使其易于阅读。
在第5章中,你将学习如何使用if语句在不同的条件下采取不同的措施;如何将一组较复杂的条件测试组合起来,并在满足特定条件时采取相应的措施。你还将学习如何在遍历列表时,通过使用if语句对特定元素采取特定的措施。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值