1 for-in 循环
magicians = ['alice','david','carolina']
for magician in magicians:
print(magician)
2 用range()生成一系列数字
for value in range(1,5):
print(value)
#输出 1 2 3 4
3 用range()和list()生成数字列表,range()可以设置步长
b = list(range(1,6))
print(b) # b为列表,[1,2,3,4,5]
even_number = list(range(2,11,2))
print(even_number)
4 数字列表计算
>>> digits = [1,2,3,4,5,6,7,8,9,0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
5 列表解析
>>> squares = [value**2 for value in range(1,11)]
>>> print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
6 切片,范围是左闭右开
players = ['charles','martina','florence','eli']
print(players[0:3]) # ['charles', 'martina', 'florence']
print(players[-3:]) # ['martina','florence','eli']
7 列表赋值是引用赋值,任何一个改变是两个都改变;切片赋值是参数赋值,任何一个改变都不会影响另外一个
>>> my_foods = ['pizza','falafel','carrot cake']
>>> friend_foods = my_foods # 引用赋值
>>> my_foods
['pizza', 'falafel', 'carrot cake']
>>> friend_foods
['pizza', 'falafel', 'carrot cake']
>>> friend_foods.append('kfc')
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> my_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> friend_foods = my_foods[:] # 参数赋值
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> friend_foods.append('kfc2')
>>> my_foods
['pizza', 'falafel', 'carrot cake', 'kfc']
>>> friend_foods
['pizza', 'falafel', 'carrot cake', 'kfc', 'kfc2']
8 元组是不可变的列表,用括号 () 表示
>>> dimensions = (200,500)
>>> print(dimensions[0])
200
>>> print(dimensions[1])
500
>>> dimensions[0] = 12 # 元组不可修改
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
9 虽然不能修改元组的元素,但是可以给元组的变量重新赋值
>>> a = (1,2)
>>> a = (3,4)
>>> a
(3, 4)