文章目录
- Python入门之操作列表
- 三、操作列表
- 3.1 遍历整个列表
- 3.1.1 深入研究循环
- 3.1.2 在for循环中执行更多操作
- 3.1.3 在for循环结束后执行一些操作
- 3.2 避免缩进错误
- 3.2.1 忘记缩进
- 3.2.2 忘记缩进额外的代码行
- 3.2.3 不必要的缩进
- 3.2.4 循环后不必要的缩进
- 3.2.5 遗漏了冒号
- 3.3 创建数值列表
- 3.3.1 使用函数range()
- 3.3.2 使用range() 创建数字列表
- 3.3.3 对数字列表执行简单的统计计算
- 3.3.4 列表解析
- 3.4 使用列表的一部分
- 3.4.1 切片
- 3.4.2 遍历切片
- 3.4.3 复制列表
- 3.5 元组
- 3.5.1 定义元组
- 3.5.2 遍历元组中的所有值
- 3.5.3 修改元组变量
- 3.6 设置代码格式
- 3.#### 5.1 格式设置指南
- 3.5.2 缩进
- 3.5.3 行长
- 3.5.4 空行
Python入门之操作列表
三、操作列表
3.1 遍历整个列表
对列表中的每个元素都执行相同的操作时,可使用Python中的for循环
。
>>> magicians = ['alice', 'david', 'carolina']
>>> for magician in magicians:
... print(magician)
alice
david
carolina
3.1.1 深入研究循环
对列表中的每个元素,都将执行循环指
定的步骤,而不管列表包含多少个元素。
编写for循环
时,可以给依次与列表中每个值相关联的临时变量指定任意名称。
使用单数和复数式名称,可帮助你判断代码段处理的是单个列表元素还是整个列表。
3.1.2 在for循环中执行更多操作
在for循环
中,可对每个元素执行任何操作。
>>> magicians = ['alice', 'david', 'carolina']
>>> for magician in magicians:
... print(f"{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!
每个缩进的代码行都是循环的一部分,将针对列表中的每个值都执行一次。
>>> 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")
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.
3.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(f"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.2 避免缩进错误
Python根据缩进来判断代码行与前一个代码行的关系.
Python通过使用缩进让代码更易读。简单地说,它要求你使用缩进让代码整洁而结构清晰。在较长的Python程序中,你将看到缩进程度各不相同的代码块,从而对程序的组织结构有大致的认识。
3.2.1 忘记缩进
如果忘记缩进, Python会提醒你。
>>> magicians = ['alice', 'david', 'carolina']
>>> for magician in magicians:
... print(magician)
File "magicians.py", line 3
print(magician)
^
IndentationError: expected an indented block
3.2.2 忘记缩进额外的代码行
如果你预期某项操作将针对每个列表元素都执行一次,但它总共只执行了一次,请确定需要将一行还是多行代码缩进。
3.2.3 不必要的缩进
如果你不小心缩进了无须缩进的代码行,Python将指出这一点。
>>> message = "Hello Python world!"
>>> print(message)
File "hello_world.py", line 2
print(message)
^
IndentationError: unexpected indent
3.2.4 循环后不必要的缩进
这些代码将针对每个列表元素重复执行。在有些情况下,这可能导致Python报告语法错误,但在大多数情况下,这只会导致逻辑错误。
3.2.5 遗漏了冒号
>>> magicians = ['alice', 'david', 'carolina']
>>> for magician in magicians
>>> print(magician)
3.3 创建数值列表
列表非常适合用于存储数字集合,而Pythonᨀ供了很多工具,可帮助你高效地处理数字列表。
3.3.1 使用函数range()
Python函数range()
让你能够轻松地生成一系列数。
函数range()
让Python从指定的第一个值开始数,并在到达你指定的第二个值时停止。因为它在第二个值处停止,所以输出不包含该值(这里为5。
>>> for value in range(1, 5):
... print(value)
1
2
3
4
使用range()
时,如果输出不符合预期,请尝试将指定的值加1或减1。
调用函数range()
时,也可只指定一个参数,这样它将从0开始。例如,range(6) 返回数0~5。
3.3.2 使用range() 创建数字列表
要创建数字列表,可使用函数list()
将range()
的结果直接转换为列表。
>>> numbers = list(range(1, 6))
>>> print(numbers)
[1, 2, 3, 4, 5]
使用函数range()
时,还可指定步长。函数range()
从2开始数,然后不断加2,直到达到或超过终值(11)
>>> even_numbers = list(range(2, 11, 2))
>>> print(even_numbers)
[2, 4, 6, 8, 10]
3.3.3 对数字列表执行简单的统计计算
有几个专门用于处理数字列表的Python函数.
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
3.3.4 列表解析
列表解析 将for循环
和创建新元素的代码合并成一行,并自动附加新元素。
这里的for语句
末尾没有冒号。
>>> squares = [value**2 for value in >>> range(1, 11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3.4 使用列表的一部分
3.4.1 切片
要创建切片,可指定要使用的第一个元素和最后一个元素的索引。
与函数range()
一样,Python在到达第二个索引之前的元素后停止。
>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> print(players[0:3])
['charles', 'martina', 'michael']
如果没有指定第一个索引,Python将自动从列表开头开始.
要让切片终止于列表末尾,也可使用类似的语法。
>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> print(players[:4])
['charles', 'martina', 'michael', 'florence']
>>> print(players[2:])
['michael', 'florence', 'eli']
>>> print(players[-3:])
['michael', 'florence', 'eli']
3.4.2 遍历切片
要遍历列表的部分元素,可在for循环
中使用切片。
>>> players = ['charles', 'martina', 'michael', 'florence', 'eli']
>>> print("Here are the first three players on my team:")
Here are the first three players on my team:
>>> for player in players[:3]:
... print(player.title())
Charles
Martina
Michael
3.4.3 复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )。
>>> my_foods = ['pizza', 'falafel', 'carrot cake']
>>> friend_foods = my_foods[:]
>>> print(my_foods)
['pizza', 'falafel', 'carrot cake']
>>> print(friend_foods)
['pizza', 'falafel', 'carrot cake']
3.5 元组
有时候你需要创建一系列不可修改的元素,元组可以满足这种需求。
3.5.1 定义元组
元组看起来很像列表,但使用圆括号而非中括号来标识。定义元组后,就可使用索引来访问其元素,就像访问列表元素一样。
来尝试修改元组dimensions 的一个元素
>>> dimensions = (200, 50)
>>> print(dimensions[0])
200
>>> print(dimensions[1])
50
>>> dimensions[0] = 250
Traceback (most recent call last):
File "dimensions.py", line 2, in <module>
dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment
严格地说,元组是由逗号标识的,圆括号只是让元组看起来更整洁、更清晰。如果你要定义只包含一个元素的元组,必须在这个元素后面加上逗号.
my_t = (3,)
3.5.2 遍历元组中的所有值
像列表一样,也可以使用for 循环来遍历元组中的所有值。
>>> dimensions = (200, 50)
>>> for dimension in dimensions:
... print(dimension)
200
50
3.5.3 修改元组变量
虽然不能修改元组的元素,但可以给存储元组的变量赋值。
>>> dimensions = (200, 50)
>>> for dimension in dimensions:
... print(dimension)
200
50
>>> dimensions = (400, 100)
>>> for dimension in dimensions:
... print(dimension)
400
100
3.6 设置代码格式
3.#### 5.1 格式设置指南
PEP 8
是最古老的PEP之一,向Python程序员ᨀ供了代码格式设置指南
3.5.2 缩进
PEP 8
建议每级缩进都使用四个空格。这既可ᨀ高可读性,又留下了足够的多级缩进空间。
3.5.3 行长
PEP 8
中有关行长的指南并非不可逾越的红线,有些小组将最大行长设置为99字符。
3.5.4 空行
要将程序的不同部分分开,可使用空行。你应该使用空行来组织程序文件,但也不能滥用。