python数字列表与元组

对数字列表执行简单的统计计算
数字列表的最大值、 最小值和总和
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits) 0
max(digits) 9
sum(digits) 45
列表解析
squares = [value2 for value in range(1,11)]
print(squares)
for循环为for value in range(1,11),将值1~10提供给表达式value
2。这里的for 语句末尾没有冒号。
结果
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
使用列表的一部分
切片
players = [‘charles’, ‘martina’, ‘michael’, ‘florence’, ‘eli’]  print(players[0:3])
输出也是一个列表
[‘charles’, ‘martina’, ‘michael’]
没有指定第一个索引,从列表头开始:
players = [‘charles’, ‘martina’, ‘michael’, ‘florence’, ‘eli’] print(players[:4])
[‘charles’, ‘martina’, ‘michael’, ‘florence’]
输出最后三个可使用players[-3:]:
遍历切片
遍历列表的部分元素,在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
复制列表
复制列表,创建一个包含整个列表的切片,同时省略起始索引和终止索引([:])。
始于第一个元素,终止于最后一个元素的切片,即复制整个列表。
my_foods = [‘pizza’, ‘falafel’, ‘carrot cake’] 
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:
[‘pizza’, ‘falafel’, ‘carrot cake’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’]
元组
不可变的列表为元组
元组用圆括号而不是方括号
dimensions = (200, 50) 
print(dimensions[0])
print(dimensions[1])
输出
200
50
遍历元组中的所有值
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
输出
200
50
修改元组变量
不能修改元组的元素,可以给存储元组的变量赋值,可重新定义整个元组
dimensions = (200, 50)
print(“Original dimensions:”)
for dimension in dimensions:
print(dimension)
#修改元素
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
#两次输出分别为
Original dimensions:
200 50
Modified dimensions:
400 100

你可能感兴趣的:(python数字列表与元组)