文章目录
4.1 遍历整个列表
for循环
magicians=['alice', 'david', 'carolina']
for magician in magicians:
print(magician)#别忘了缩进
4.3创建数值列表
4.3.1函数range()
range() 能生成一系列数字
for value in range(1,5)
print(value)
1
2
3
4
指定的第一个值开始数,并在到达你指定的第二个值 后停止,因此输出不包含第二个值
4.3.2 创建数字列表
1.要创建数字列表,可使用函数list() 将range() 的结果直接转换为列表
numbers=list(range(1,5))
print(numbers)
[1,2,3,4]
2.使用函数range() 时,还可指定步长
even_numbers=list(range(2,11,2))
print(even_numbers)
函数range() 从2开始数,然后不断地加2,直到达到或超过终值(11),因此输出如下
[2.4,6,8,10]
3.可以创建任何需要的数字集
squares=[]
for value in range(1,11)
squares.append(value**2)#**表示平方
print(squares)
4.3.3对数字列表执行简单的统计计算
专门用于处理数字列表的Python函数
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>>> min(digits)
0
>>>max(digits)
>9
>>>> sum(digits)
>45
4.3.4列表解析
squares = [value**2 for value in range(1,11)]
print(squares)
定义一个表达式,用于生成你要存储到列表中的值
请注意,这里的for 语句末尾没有冒号
4.4 使用列表的一部分
4.4.1 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
与函数range() 一样,Python在到达你指定的第二个索引前面的元素后停止
['charles', 'martina', 'michael']
1.如果你没有指定第一个索引,Python将自动从列表开头开始。未指定最后一个索引则到最后一个元素结束。
2.负数索引返回离列表末尾相应距离的元素,因此你可以输出列表末尾的任何切片。 例如,如果你要输出名单上的最后三名队员,可使用切片players[-3:]
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])
['charles', 'martina', 'michael', 'florence']
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())
Here are the first three players on my team:
Charles
Martina
Michael
4.4.3 复制列表
要复制列表,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引([:] )。
❶ my_foods = ['pizza', 'falafel', 'carrot cake']
❷ friend_foods = my_foods[:]
my_foods = ['pizza', 'falafel', 'carrot cake']
#这行不通
❶ friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
这种语法实际上是让Python将新变量friend_foods 关联到包含 在my_foods 中的列表,因此这两个变量都指向同一个列表。
4.5元组
创建一些不可修改的元素。Python将不能修改的值称为不可变的 ,而不可变的列表被称为元组。
4.5.1 定义元组
使用圆括号而不是方括号来标识。
list=(1,2)
print(list[0])
print(list[1])
0
1
4.5.2 遍历元组中所有的值
同列表一样。
4.5.3 修改元组变量
重新赋值即可
❶ dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
❷ dimensions = (400, 100)
❸ print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)