python —— 操作列表
遍历列表
适合用于存储在程序运行期间可能变化的数据集
在列表中,对每个元素执行相同胡操作,可以使用for循环。
在for循环中,每个缩进胡代码行都是循环的一部分,将针对列表中的每个值都执行一次,没有缩进的代码都只执行一次
magicans = ['alice','david','carolina']
for magician in magicians:
print(magician)
创建数值列表
函数range()让Python从指定的第一个值开始数,在到达第二个值时停止(不包含第二个值)
列表解析
列表解析将for循环和创建新元素的代码合并成一行,并自动附加新元素。
使用列表
切片:处理列表的部分元素,Python称之为切片
创建切片,可指定要使用的第一个元素和最后一个元素的索引,Python在到达第二个索引之前的元素后停止
players = ['charles','martina','michael','florence','eli']
print(players[0:3])
输出结果:
['charles','martina','michael']
遍历切片:遍历列表的部分元素,可以在for循环中使用切片
players = ['charles','martina','michael','florence','eli']
print("Here are the first three players on my team:")
for players in players[:3]:
print(player.title())
输出结果:
Here are the first three players on my team:
Charles
Martina
Michael
复制列表:创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([ : ]),这让python创建始于第一个元素,终止于最后一个元素的切片
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
遍历元组中的所有值:使用for循环
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,10)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
输出结果:
Original dimensions:
200
50
Modified dimensions:
400
100