Python 学习笔记(三)
Aug 25, 2016
使用函数
range()
生成一系列的数字:1
2
3
4
5
6
7for value in range(1, 5):
print(value)
# 结果为:
# 1
# 2
# 3
# 4还可以指定步长,使用函数
list()
将range()
的值直接转换为列表:1
2even_number = list(range(2, 11, 2))
print(even_number) # [2, 4, 6, 8, 10]
找出数字列表的最大值、最小值和总和:
1
2
3
4digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) # 0
print(max(digits)) # 9
print(sum(digits)) # 45列表解析:
1
2squares = [value ** 2 for value in range(1, 11)]
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]列表切片访问:
1
2
3
4
5players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4]) # ['martina', 'michael', 'florence']
print(players[:3]) # ['charles', 'martina', 'michael']
print(players[3:]) # ['florence', 'eli']
print(players[-3:]) # 打印最后三个 ['michael', 'florence', 'eli']- 没有指定起始索引,从开头开始提取
- 没有指定终止索引,一直到列表末尾
列表的复制:
利用切片复制
1
2
3
4
5
6
7
8
9
10
11my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods) # ['pizza', 'falafel', 'carrot cake', 'cannoli']
print("\nMy friend's favorite foods are:")
print(friend_foods) # ['pizza', 'falafel', 'carrot cake', 'ice cream']两个变量同时关联同一列表
1
2
3
4
5
6
7
8
9
10
11my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods) # ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
print("\nMy friend's favorite foods are:")
print(friend_foods) # ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
列表是可以修改的,不可变的列表称为元组
1
2dimensions = (200, 50)
dimensions[0] = 250 # 出现错误