《Python 编程 从入门到实践》 第四章 操作列表

第四章 操作列表

4.1 遍历整个列表
如 使用for 循环来打印魔术师名单中的所有名字:
magicians = [‘alice’, ‘david’, ‘carolina’]
for magician in magicians: #依次从magicians中取出元素放在magician中(magician可换成任意变量)
  print(magician) #注意for后面的冒号:

4.1.2 在for 循环中执行更多的操作
magicians = [‘alice’, ‘david’, ‘carolina’]
for magician in magicians:
print(magician.title() + “, that was a great trick!”) # for循环不用写{},但是要缩进
print("I can’t wait to see your next trick, " + magician.title() + “.\n”)

4.1.3 在for 循环结束后执行一些操作
写在for循环外面即可,即不缩进

4.2 避免缩进错误

4.2.1 忘记缩进
如:
magicians = [‘alice’, ‘david’, ‘carolina’]
for magician in magicians:
print(magician)
会报错 IndentationError: expected an indented block # 期望一个缩进的块

4.2.3 不必要的缩进
message = “Hello Python world!”
  print(message)
会报错:IndentationError: unexpected indent

若是代码逻辑缩进错误,则不会报错

4.2.5 遗漏了冒号
magicians = [‘alice’, ‘david’, ‘carolina’]
for magician in magicians
print(magician)
会报错:SyntaxError: invalid syntax # 非法语句

4.3 创建数值列表

4.3.1 使用函数range()

for value in range(1,5): # 从1到4
print(value)

1
2
3
4 #注意并不会打印 5

4.3.2 使用range() 创建数字列表
numbers = list(range(1,6))
print(numbers)

[1, 2, 3, 4, 5]

even_numbers = list(range(2,11,2)) # 从2开始,每次增加2,直到终止11
print(even_numbers)

[2, 4, 6, 8, 10]

squares = [] #申请空列表
for value in range(1,11): #列表1到10之间循环
  squares.append(value**2) # 值的平方,存在空列表的末尾
print(squares)

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

4.3.3 对数字列表执行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits) # 最小值,不用打印,也能直接输出,也可打印
max(digits) # 最大值
sum(digits) # 总和

4.3.4 列表解析
squares = [value**2 for value in range(1,11)] #太简洁了!注意此时的for循环不带冒号
print(squares)

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

4.4 处理列表部分元素

4.4.1 切片
players = [‘charles’, ‘martina’, ‘michael’, ‘florence’, ‘eli’]
print(players[0:3]) #输出前三个元素

[‘charles’, ‘martina’, ‘michael’]

print(players[:4]) # 从列表开头开始切
print(players[2:]) # 切到末尾

print(players[-3:]) #打印最后三个,列表循环

4.4.2 遍历切片
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 复制列表
用切片复制:friend_foods = my_foods[:] #把my_foods列表复制到friend_foods列表
直接赋值:friend_foods = my_foods # 和切片的区别是它会使两个列表始终保持一致

4.5 元组

4.5.1 定义元组
元组是不可变的列表,其值不可修改
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])

200
50

4.5.2 遍历元组中的所有值
和列表一样
dimensions = (200, 50)
for dimension in dimensions:
  print(dimension)

4.5.3 修改元组变量
即重新给元组赋值,会覆盖原先的
dimensions = (200, 50)
dimensions = (400, 100)

发布了75 篇原创文章 · 获赞 1 · 访问量 2069

猜你喜欢

转载自blog.csdn.net/Rhao999/article/details/103891758