# :如何高效地处理列表中的元素;如何使用for循环遍历列表,Python
# 如何根据缩进来确定程序的结构以及如何避免一些常见的缩进错误;如何创建简单的数字列表,
# 以及可对数字列表执行的一些操作;如何通过切片来使用列表的一部分和复制列表。你还学习了
# 元组(它对不应变化的值提供了一定程度的保护),以及在代码变得越来越复杂时如何设置格式,
# 使其易于阅读。
#遍历列表
magicians = ['alice', 'david', 'carolina']
print(magicians)
#使用单数和复数式名称,可帮助你判断代码段处理的是单个列表元素还是整个列表
# 从列表magicians中取出一个名字,并将其存储在变量magician中
for magician in magicians:
#Python根据缩进来判断代码行与前一个代码行的关系
print(magician)
print(magician.title() + ", that was a great trick")
print("I can't wait see your next trick, " + magician.title() + ".\n")
print("Thank you, everyone. That was a great magic show!")
#创建数字列表
for value in range(1,5):
print(value)
#可使用函数list()将range()的结果直接转换为列表
m_numbers = list(range(1,6))
print(m_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) #将新计算得到的平方值附加到列表squares末尾
print(squares)
# 找出数字列表的最大值、 最小值和总和
print(min(squares))
print(max(squares))
print(sum(squares))
# 列表解析将for循环和创建新元素的代码合并成一行
squares_1 = [value_1**2 for value_1 in range(1,11)]
print(squares_1)
#切片
# 1 指定开始和结束
print(squares[1:3])
# 2 不指定开始,默认从列表开头
print(squares[:3])
# 3 不指定结束,默认到列表末尾
print(squares[1:])
#遍历切片
for square in squares[:3]:
print(square)
#复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
#这行不通 friend_foods = my_foods
friend_foods = my_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)
#Python将不能修改的值称为不可变的,而不可变的列表被称为元组
# 元组看起来犹如列表,但使用圆括号而不是方括号来标识
dimensions = (200, 50, 100)
print(dimensions[0])
print(dimensions[1])
#dimensions[0] = 250 TypeError: 'tuple' object does not support item assignment
# 遍历元组
for dimension in dimensions:
print(dimension)
python ch4 操作列表
于 2024-03-25 16:51:02 首次发布