for循环依次遍历
PS:使用单数和复数式名称,可帮助你判断代码段处理的是单个列表元素还是整个列表
magicians = ['alice', 'david', 'carolina']
for magican in magicians:
print(magican)
alice
david
carolina
c风格for循环也可以
for i in range(len(magicians)):
print(magicians[i])
alice
david
carolina
函数range()可上传一系列数字,不制定首元素,默认从0开始
print(range(5))
range(0, 5)
range() 可转化为列表
PS:生成的列表元素为range的前闭后开区间,这与其他语言保持一致
numbers = list(range(1,6))
print(numbers)
[1, 2, 3, 4, 5]
range接受第三个参数,表示步长,此时必须指明起始位置
even_numbers = list(range(2,15,2))
print(even_numbers)
[2, 4, 6, 8, 10, 12, 14]
步长可以是复数,但记得这样做要保证起始位置大于末尾位置
odd_numbers = list(range(50,29,-3))
print(odd_numbers)
[50, 47, 44, 41, 38, 35, 32]
数值列表简单统计
print(max(even_numbers), min(numbers), sum(even_numbers))
14 1 56
列表解析创建列表
squares = [value ** 2 for value in range(1,11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
计算1到1000000的累加和
sum([value for value in range(1,1000001)])
500000500000
可以用冒号(:)来进行“切片”操作
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])
print(players[:4])
print(players[1:4])
print(players[2:])
print(players[-2:])
print(players[::-2])
['charles', 'martina', 'michael']
['charles', 'martina', 'michael', 'florence']
['martina', 'michael', 'florence']
['michael', 'florence', 'eli']
['florence', 'eli']
['eli', 'michael', 'charles']
列表的复制
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
print(my_foods)
print(friend_foods)
my_foods.append("canoli")
friend_foods.append("ice cream")
print(my_foods)
print(friend_foods)
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake']
['pizza', 'falafel', 'carrot cake', 'canoli']
['pizza', 'falafel', 'carrot cake', 'ice cream']
徜若直接用等号(=)进行列表拷贝,将不能得到一个新的列表,这是因为列表名仅是一个指向列表的指针
类比C的指针赋值,浅拷贝与深拷贝
self_foods = my_foods
my_foods.append('ice cream')
print(my_foods)
print(self_foods)
['pizza', 'falafel', 'carrot cake', 'canoli', 'ice cream']
['pizza', 'falafel', 'carrot cake', 'canoli', 'ice cream']
圆括号() 可创建元组,元组是不可改边的列表
dimensions = (200,50)
print(dimensions[0],dimensions[1])
200 50
元组内容不可修改,但是元素本身却可以多次赋值
dimensions = (400,20)
print(dimensions[0],dimensions[1])
400 20
网友评论