for循环遍历列表的所有元素
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
输出:
alice
david
carolina
对用于存储列表中每个值的临时变量,通常指定描述单个列表元素的名称
for cat in cats:
for dog in dogs:
for item in list_of_items:
创建数值列表range()函数生成一系列数字(左闭右开)
for value in range(1,5):
print(value)
输出:
1
2
3
4使用list()函数创建数字列表,range()作为list()的参数
numbers = list(range(1,5))
print(numbers)
输出:
[1, 2, 3, 4]
为range()函数指定步长:
even_numbers = list(range(2,11,2)) #第三个参数为步长
print(even_numbers)
输出:
[2, 4, 6, 8, 10]min()函数、max()函数、sum()函数用于数字列表统计计算
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
输出:
0
9
45列表解析:将for循环和创建新元素的代码合并成一行
squares = [value ** 2 for value in range(1, 11)]
print(squares)
输出:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
注:for语句末尾没有冒号
使用列表的一部分创建切片:指定第一个和最后一个元素的索引,左闭右开
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[:4])
print(players[2:])
print(players[-3:])
输出:
['charles', 'martina', 'michael']
['charles', 'martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['michael', 'florence', 'eli']遍历切片:使用for循环
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[:3]:
print(player.title())
输出:
Charles
Martina
Michael复制列表:创建一个包含整个列表的切片
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
输出:
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake', 'cannoli']
['pizza', 'falafel', 'carrot cake', 'ice cream']
注:在不使用切片的情况下复制列表→两个列表变量指向同一列表
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
print(friend_foods)
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods)
print(friend_foods)
输出:
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
元组
列表可变,元组不可变
定义元组圆括号
使用索引来访问
dimensions = (200,50)
print(dimensions[0])
输出:
dimensions = (200,50)
print(dimensions[0])
不可修改元组中元素
dimensions = (200,50)
dimensions[0] = 250
输出:
Traceback (most recent call last):
File "hello_world.py", line 168, in
dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment
遍历元组中所有值
dimensions = (200,50)
for dimension in dimensions:
print(dimension)
输出:
200
50
修改元组变量
dimensions = (200,50)
dimensions = (400,100)
for dimension in dimensions:
print(dimension)
输出:
400
100
设置代码格式易于阅读 > 易于编写
缩进:不可混用制表符Tab和空格
行长:每行不超过80字符(注释不超过72字符)
配置文本编辑器:按制表符时插入4个空格;显示垂直参考线以遵守行长
空行:不影响运行