第四章 操作列表(for循环)
作者:互联网
第四章 操作列表
4.1遍历整个列表
使用for循环打印
将列表heros的元素与he(随便取一个变量)相关联,打印赋给变量he的内容
heros = ['zhangsan','yaso','mangzai']
for he in heros:
print(he)
zhangsan
yaso
mangzai
4.1.1 深入循环研究
for he in heros:
这行代码让python获取列表heros中的第一个值‘zhangsan’,并将其与变量’he’相关联,接下来读取下一行代码
print(he)
让打印’he’的值,依然是’zhangsan’,该列表还包含其他值,python返回到循环的第一行
for he in heros:
print(he) # 然后获取第二个元素关联'he',再打印,以此类推
循环中有多少个元素就执行多少次循环,直到最后一个元素
至于变量也是可以随便定名称,但是用单数和双数区分可以更有可读性:
for cat in cats: for message in messages
4.1.2 在for循环中执行更多操作
附加消息
heros = ['zhangsan','yaso','mangzai']
for hero in heros:
print(f"{hero.title()},who is a good hero")
for hero in heros:
print(f"{hero.title()},who is a good hero")
print(f"I can't wait to see your next performance,{hero.title()}.\n")
4.1.3在for循环结束后执行一些操作
for hero in heros:
print(f"{hero.title()},who is a good hero")
print(f"I can't wait to see your next performance,{hero.title()}.\n")
print("Thank you,everyone, that was a good game show!") # 主要看缩进
看缩进辨别是否在循环里,有缩进的在循环里,没有的是全局的语句
4.2避免缩进错误
python中根据缩进来判断代码行与前一个代码行的关系
4.2.1忘记缩进
对于for循环的组成代码行必须缩进
heros = ['zhangsan','yaso','mangzai']
for hero in heros:
print(hero) # expected an indented block(应为缩进块)
4.2.2忘记缩进额外的代码行
忘了某一行
for hero in heros:
print(f"{hero.title()},who is a good hero")
print(f"I can't wait to see your next performance,{hero.title()}.\n")
这是一个逻辑错误,语法合理,但结果不符合预期
4.2.3不必要的缩进
message = 'Hello world'
print(message) # unexpected indent(不被期望的缩进)
4.2.4循环后不必要的缩进
for hero in heros:
print(f"{hero.title()},who is a good hero")
print(f"I can't wait to see your next performance,{hero.title()}.\n")
print("Thank you,everyone, that was a good game show!")
逻辑错误
4.2.5 遗漏了冒号(重要)
for那一行末尾要跟冒号:
for hero in heros # invalid syntax(无效语法)
print(f"{hero.title()},who is a good hero")
4.2.6练习
4-1 披萨
pizzas = ['Sausage pizza','Cheese pizza','Corn pizza']
for pizza in pizzas:
print(pizza)
print(f"i love {pizza}.\n")
print("I really like pizza!")
4-2 动物
dogs = ['柯基','二哈','拉布拉多','牧羊犬']
for dog in dogs:
print(f"{dog}喜欢吃骨头")
print("他们都是很好的宠物狗")
4.3创建数值列表
4.3.1 使用函数range()
生成数据
for num in range(1,5): # 1开始,5截至(不包括5)
print(num)
range只打印了1-4,由于编程语言中常见的差一行为的结果,函数
rangr()
指定第一个数开始,第二个数处停止
所以要输出1~5得用range(1,6)
for num in range(1,6):
print(num)
调用`range()`时,也可指定一个参数,这样它将从0开始。
for num in range(5): # 从0开始五个数
print(num)
4.3.2 使用range()创建数字列表
可以用list()
函数直接将range()的结果转换为列表
number = list(range(5))
print(number)
[0, 1, 2, 3, 4]
range()函数还可以指定步长range(start,stop,step)
num = list(range(5,18,3)) # 从5开始,每次+3,到18结束
print(num)
[5, 8, 11, 14, 17]
用range()可以创建任何需要的数集,活用for,列表操作的函数,增加删除等
如:创建由前十个数平方组成的列表
squares = [] # 创个空列表,到时候用append添加
for value in range(1,11):
square = value ** 2
squares.append(square) # 每次的结果都添加到列表中,用向末尾加的方法
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
squares.append(value ** 2) #简洁写法
4.3.3 对数字列表进行简单的统计计算
函数:min(),sum(),max()
digits = []
for num in range(10):
digits.append(num)
print(digits)
max(digits)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9
min(digits)
0
sum(digits)
45
4.3.4 列表解析
将for
循环和创建新元素的代码合成一行,并自动附加新元素
格式:list = [要存数据的表达式 for value in range()]
注意这里的for循环没有冒号
squares = [value ** 2 for value in range(1,10)] # 没有冒号
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
4.3.5 练习
4-3 数到20
for num in range(1,21):
print(num)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
练习4-4:一百万
million = [value for value in range(1,10001)] # 100万太大输不出来
print(million)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ......]
4-5 100万求和
million = [value for value in range(1,1000001)]
print(min(million))
print(max(million))
print(sum(million)) # 秒出
1
1000000
500000500000
4-6 奇数
odd_num = list(range(1,20,2))
for o in odd_num:
print(o)
1
3
5
7
9
11
13
15
17
19
4-7 3的倍数
three = list(range(3,31,3))
for num in three:
print(num)
3
6
9
12
15
18
21
24
27
30
4-8 立方
cube = [num ** 3 for num in range(1,11)]
for value in cube:
print(value)
1
8
27
64
125
216
343
512
729
1000
4.4 使用列表的一部分(切片)
4.4.1 切片
要创建切片,可指定要使用的起始元素和终止元素
一般就是[a,b],a是访问起始元素-1,b就是终止元素,如访问3.4个 【2:4】
players = ['A','B','C','D','E']
print(players[0:3]) # 输出第1~3个
['A', 'B', 'C']
# 指定输出第3,4个元素
print(players[2:4])
['C', 'D']
不指定起始默认从表头开始
# 不指定起始默认从表头开始
print(players[:4])
['A', 'B', 'C', 'D']
# 要让切片终止于末尾,同样操作
print(players[2:])
['C', 'D', 'E']
# 上章的负索引也是同样,如输出后三个元素
print(players[-3:])
['C', 'D', 'E']
# 还可以指定步长,如访问第2到5个元素,间隔为2
print(players[1:5:2])
['B', 'D']
4.4.2 遍历切片
players = ['A','B','C','D','E']
print("Here are the first three players on my team")
for memb in players[:3]:
print(memb)
Here are the first three players on my team
A
B
C
4.4.3 复制列表
创建一个包含整个列表的切片[:]通过不加起始和终止索引
my_foods = ['noodles','cake','pizza','bread']
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:
['noodles', 'cake', 'pizza', 'bread']
My friend's favorite foods are:
['noodles', 'cake', 'pizza', 'bread']
# 核实是否是两个列表,分别添加东西
my_foods.append('water')
friend_foods.append("cola")
print(my_foods)
print(friend_foods)
['noodles', 'cake', 'pizza', 'bread', 'water']
['noodles', 'cake', 'pizza', 'bread', 'cola']
复制必须切片,不切片直接=,会导致两个代表同一个列表,对两个表的操作其实是在操作用一个表
my_foods = ['noodles','cake','pizza','bread']
my_foods = friend_foods
my_foods.append('water')
friend_foods.append("cola")
print(my_foods)
print(friend_foods)
['noodles', 'cake', 'pizza', 'bread', 'cola', 'water', 'cola']
['noodles', 'cake', 'pizza', 'bread', 'cola', 'water', 'cola']
4.4.4 练习
4-10切片
players = ['noodles', 'cake', 'pizza', 'bread', 'cola', 'water', 'cola']
print("The first three items in the list are:")
print(players[:3])
print("\nThree items from the middle of the list are:")
print(players[2:5])
print("\nThe last three items in the list are:")
print(players[-3:])
The first three items in the list are:
['noodles', 'cake', 'pizza']
Three items from the middle of the list are:
['pizza', 'bread', 'cola']
The last three items in the list are:
['cola', 'water', 'cola']
4-11 你的皮萨,我的披萨
my_pizzas = ['Sausage pizza','Cheese pizza','Corn pizza']
friend_pizzas = my_pizzas[:]
my_pizzas.append("beef pizza")
friend_pizzas.append("cola pizza")
print("my favorite pizzas are:")
for pizza in my_pizzas:
print(f"- {pizza}")
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(f"- {pizza}")
my favorite pizzas are:
- Sausage pizza
- Cheese pizza
- Corn pizza
- beef pizza
My friend's favorite pizzas are:
- Sausage pizza
- Cheese pizza
- Corn pizza
- cola pizza
4.5 元组
⭐列表非常适合用于存储在程序运行期间可能变化的数据集。列表是可修改的
⭐元组则是不可变的列表。Python将不能修改的值称为不可变的
4.5.1 定义元组
元组看起来像列表,但用()圆括号而不是[]方括号,其他的索引,遍历和列表一样
dimensions = (200,50) # 两个元素的元组
print(dimensions[0])
print(dimensions[1])
200
50
# 尝试修改
dimensions = (200,50)
dimensions[0] = 255 #'tuple'(元组) object does not support item assignment不支持赋值
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-30-99dbc19ec1e2> in <module>
1 # 尝试修改
2 dimensions = (200,50)
----> 3 dimensions[0] = 255 #'tuple'(元组) object does not support item assignment不支持赋值
TypeError: 'tuple' object does not support item assignment
注意:严格的说,元组是由逗号标识的,()只是为了美观。如果只要定义一个元素的元组,必须在这个元素后面加上逗号:
my_t = (3,)
# 试验
neirong = (1,2)
hao = (3,)
women = 4,5,7 # 不加括号也没有问题
print(neirong)
print(hao)
print(women[1])
print(women)
(1, 2)
(3,)
5
(4, 5, 7)
4.5.2遍历元组中的所有值
num = (4,7,8,9)
for v in num:
print(v)
4
7
8
9
4.5.3修改元组中的变量
虽然不能改变元组的元素,但能给这些元素重新赋值来改变
num = (4,7,8,9)
print("original num:")
for v in num:
print(v)
num = (2,5,3,3)
print("modified num:")
for v in num:
print(v)
original num:
4
7
8
9
modified num:
2
5
3
3
4.5.4 练习
4-13 自助餐
foods = ('noodles', 'cake', 'pizza', 'bread', 'cola')
for con in foods:
print(con)
noodles
cake
pizza
bread
cola
foods[1] = 'xuebi'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-378c38c533e1> in <module>
----> 1 foods[1] = 'xuebi'
TypeError: 'tuple' object does not support item assignment
foods = ('noodles', 'zhou', 'milk', 'bread', 'cola')
for new in foods:
print(new)
4.6 设置代码格式
⭐缩进:每级缩进都用四个空格,一般文字文档用制表符,要防止制表符和空格混乱
⭐每行最好不要超过80字符
⭐空行在不同操作间用,空行不会影响运行,一般只用一行,不用多行
标签:num,range,列表,foods,循环,print,hero,第四章,pizza 来源: https://blog.csdn.net/xuezhale/article/details/118487761