文章目录
1. 遍历列表
- 需要对列表中的每个元素都执行相同的操作时,可使用Python中的for循环
- 操作示例:
>>> 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:
上面的cat/dog/item就是针对单个列表元素有意义的临时变量名
1.2 for 循环操作
- 在代码行for语句后面,每个缩进的代码行都是循环的一部分,将针对列表中的每个值都执行一次
- 示例1:
>>> 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!
- 示例2:
>>> 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循环结束后需要提供总结性输出或者接着执行程序必须完成的其他任务
- 在for循环后面,没有缩进的代码都只执行一次,而且不会重复执行
- cmd中演示如下:
>>> 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.
>>> print("Thank you,That was a great magic show!")
Thank you,That was a great magic show!
- pycharm中演示如下:
备注:后面若有运行分两块显示,均为使用pycharm操作,不再复述,便于代码可读
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,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,That was a great magic show!
2. 避免常见错误
2.1 遗漏冒号
for循环语句遗漏了冒号,将导致语法错误
>>> magicians = ['alice','david','carolina']
>>> for magician in magicians
File "<stdin>", line 1
for magician in magicians
^
SyntaxError: expected ':'
2.2 忘记缩进
下面演示中,print语句应缩却未缩
>>> magicians = ['alice','david','carolina']
>>> for magician in magicians:
... print(magician)
File "<stdin>", line 2
print(magician)
^
IndentationError: expected an indented block after 'for' statement on line 1
2.3 忘记缩进额外的代码行
下面演示中,第二个print语句应缩却未缩
代码是合法的,执行并未报错,但是从结果上看,犯了逻辑错误,不符合预期
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!
David,that was a great trick!
Carolina,that was a great trick!
I can't wait to see your next trick,Carolina.
2.4 不必要的缩进
下面演示中,print语句无需缩进,因为其并不隶属于前一行代码
>>> message = "Hello Python world!"
>>> print(message)
File "<stdin>", line 1
print(message)
IndentationError: unexpected indent
2.5 循环后不必要的缩进
下面演示中,第三个print语句无需缩进,它应是循环结束后的总结性语句
代码是合法的,执行并未报错,但是从结果上看,犯了逻辑错误,不符合预期
>>> 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,That was a great magic show!")
...
Alice,that was a great trick!
I can't wait to see your next trick,Alice.
Thank you,That was a great magic show!
David,that was a great trick!
I can't wait to see your next trick,David.
Thank you,That was a great magic show!
Carolina,that was a great trick!
I can't wait to see your next trick,Carolina.
Thank you,That was a great magic show!
3. 数字列表
列表非常适合于存储数字集合
3.1 range()
- range(起始数字,结尾数字,步长)
- 结尾数字在结果中不显示,只显示起始数字累加n个步长后最接近结尾数字的整数,是编程语言中常见的差一行为
- 步长不写默认为1
>>> for value in range(1,11):
... print(value)
...
1
2
3
4
5
6
7
8
9
10
>>> for value in range(1,11,2):
... print(value)
...
1
3
5
7
9
3.2 list(range())
- 使用list()将range()的结果转换为列表
>>> even_numbers = list(range(1,11,2))
>>> print(even_numbers)
[1, 3, 5, 7, 9]
- Python中两个**代表乘方运算
squares = []
for value in range(1,11,2):
square = value**2
squares.append(square)
print(squares)
[1, 9, 25, 49, 81]
3.3 max()/min()/sum()
专门用于处理数字列表的函数
>>> digits = [1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
3.4 列表解析
- 列表解析是将for循环和创建新元素的代码合成一行,并自动附加新元素
- 当你觉得编写三四行代码生成列表有点繁琐,就应考虑创建列表解析了
- 属于进阶内容
>>> squares = [value**2 for value in range(1,11,2)]
>>> print(squares)
[1, 9, 25, 49, 81]
4. 切片
是处理列表中的部分数据
4.1 切片介绍
- 下面冒号:左侧为起始索引编号,冒号:右侧为终止索引编号(右侧实际结果显示仍然具有差一行为)
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[0:3])
['charles', 'martina', 'michael']
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[0:5])
['charles', 'martina', 'michael', 'florence', 'eli']
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[2:4])
['michael', 'florence']
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[:3])
['charles', 'martina', 'michael']
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[3:])
['florence', 'eli']
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[-3:])
['michael', 'florence', 'eli']
>>> players =['charles','martina','michael','florence','eli']
>>> print(players[-1:])
['eli']
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.3 复制列表
- 要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:])
- 若friend_foods=my_foods[:] 更改为 friend_foods=my_foods 则这两个变量都指向同一个列表,结果完全一样,不符合我们要求
my_foods =['pizza','falafel','carrot cake']
friend_foods=my_foods[:]
print("My favorite foods before are:")
print(my_foods)
print("My friend's favorite foods before are:")
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("\nMy favorite foods now are:")
print(my_foods)
print("My friend's favorite foods now are:")
print(friend_foods)
My favorite foods before are:
['pizza', 'falafel', 'carrot cake']
My friend's favorite foods before are:
['pizza', 'falafel', 'carrot cake']
My favorite foods now are:
['pizza', 'falafel', 'carrot cake', 'cannoli']
My friend's favorite foods now are:
['pizza', 'falafel', 'carrot cake', 'ice cream']
5. 元组
- 列表时用于存储程序在运行期间可能变化的数据集
- 若是创建不可修改的元素的数据集,需要使用元组
- 不可改变的列表称为元组
- 元组使用圆括号标识,注意与列表使用中括号标识区分开来
5.1 定义元组
>>> dimensions = (200,50)
>>> print(dimensions[0])
200
>>> print(dimensions[1])
50
试图修改元组中的元素值,运行报错
>>> dimensions = (200,50)
>>> dimensions[0] = 250
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
5.2 遍历元组中的值
>>> dimensions = (200,50)
>>> for dimension in dimensions:
... print(dimension)
...
200
50
5.3 修改元组变量
虽然不能修改元组的元素,但可以给存储元组的变量重新赋值
dimensions = (200,50)
print("Orininal dimensions:")
for dimension in dimensions:
print(dimension)
dimensions =(400,100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
Orininal dimensions:
200
50
Modified dimensions:
400
100
6. 代码格式
- 让代码易于阅读有助你掌握程序是做什么的,也可以帮助他人理解你写的编码
- 代码被阅读的次数比写的次数多
- PEP8(Python改进提案)建议每级缩进使用四个空格
- 在程序中混合使用制表符和空格可能导致极难解决的问题,如果混合使用了,可以在编辑器重将文件中所有的制表符转为空格
- 建议每行代码不超过80字符
- 建议注释的行长不超过72字符
- 空行不会影响代码运行,但会影响代码的可读性