Python 列表(list) 使用方法汇总
2018-01-23 本文已影响18人
赵者也
- 在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
- 在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
- 使用 del 语句删除元素,使用 del 可删除任何位置处的列表元素,条件是知道其索引
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
- 使用方法 pop() 删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
- 根据值删除元素,如果知道要删除的元素的值,可使用 remove() 方法。注意:方法 remove() 只删除第一个出现的值。
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
- 使用方法 sort() 对列表进行永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
cars.sort(reverse=True) # 倒序
print(cars)
- 使用函数 sorted() 对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)
- 反转(非排序)列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
- 使用函数 len() 获得列表长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
count = len(cars)
print("cars count is " + str(count))
- 使用索引 -1,访问最后一个列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[-1])
- 使用函数 range() 生成一列数字(本例输出 1、2、3、4)
for value in range(1, 5):
print(value)
- 使用 range() 创建数字列表
numbers = list(range(1,6))
print(numbers)
- 使用 min()、max()、sum() 函数对数字列表进行简单的统计计算
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits))
print(max(digits))
print(sum(digits))
- 列表解析
squares = [value**2 for value in range(1, 11, 2)]
print(squares)
- 切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) # 第一个到第三个元素
print(players[1:4]) # 第二个到第四个元素
print(players[:4]) # 第一个到第四个元素
print(players[2:]) # 第三个到最后一个元素
print(players[-3:]) # 后三个元素
- 遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
for player in players[:3]:
print(player.title())
- 复制列表
my_foods = ['pizza', 'falafel', 'carrot cake']
my_foods_copy = my_foods # 错误的复制方法
friend_foods = my_foods[:] # 复制操作
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("My friend's favorite foods are:")
print(friend_foods)
print("My favorite foods copy are:")
print(my_foods_copy)
- 元组,元组看起来犹如列表,但使用圆括号而不是方括号来标识。定义元组后,就可以使用索引来访问其元素,就像访问列表元素一样。注意:试图修改元组元素的操作是被禁止的,因此 Python 指出不能给元组的元素赋值。虽然不能修改元组的元素,但可以给存储元组的变量赋值。因此,如果要修改前述矩形的尺寸,可重新定义整个元组:
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
print("\nModified dimensions:")
# dimensions[0] = 250 # 错误的做法
dimensions = (250, 50)
for dimension in dimensions:
print(dimension)
如果需要存储的一组值在程序的整个生命周期内都不变,可使用元组。
本文参考自 《Python 编程:从入门到实践》