1、列表操作类
插入 操作 (1)append() 在末尾追加元素
motorcycles = []
motorcycles.append('honda')
(2)insert(index,A) 在任何位置插入
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
索引-1总是返回最后一个列表元素,
删除操作
(1)del
(2)pop
(3)remove
2、其他操作
(1)排序 sort()---正序 cars.sort(reverse=True) ----逆序 方法:a.sort()
临时排序 sorted() 用法:sorted(a)
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
(2)反转排序,原来的顺序不变
cars.reverse()
(3)长度
len(cars)
遍历
(1)
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician) 循环取出放到 magician中,然后打印
数字列表
1、range函数
for value in range(1,6):
print(value) ---------生成 1到5的数字
range(2,11,2)------指定步长为2
numbers = list(range(1,6))
print(numbers) -----list把生成的数字放到了列表中
2、解析列表
squares = [value**2 for value in range(1,11)]
print(squares) ----------把好几行合成一行书写的方式
3、列表切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[1:4]) -------->['martina', 'michael', 'florence']
print(players[0:4])--------->['charles','martina', 'michael', 'florence']
print(players[-3:]) ------>打印最后三名队员的名字,即便队员名单的长度发生变化,也依然如此
for player in players[:3]:
print(player.title()) -------------->遍历前三名
复制列表
my_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)
print("\nMy friend's favorite foods are:")
print(friend_foods)------------------------------>能实现列表的复制,即改动my_foods 对friend_foods不产生影像
但是
my_foods = ['pizza', 'falafel', 'carrot cake']
#这行不通
friend_foods = my_foods--------------->这样就行不通,这样改变会全部改变