列表
一、列表的定义
bicycles = ['trek', 'cannondale', 'redline', 'specialized']print(bicycles)['trek', 'cannondale', 'redline', 'specialized']print(bicycles[0])trek
二、修改,添加和删除元素
1.修改列表元素
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles[0] = 'ducati'print(motorcycles)
2.在列表中添加元素
在列表末尾添加元素
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)motorcycles.append('ducati')print(motorcycles)
在列表中插入元素
motorcycles = ['honda', 'yamaha', 'suzuki']motorcycles.insert(0, 'ducati')print(motorcycles)
3.删除列表元素
使用del语句删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)del motorcycles[0]print(motorcycles)
使用方法pop()删除元素
pop()可删除列表末尾的元素。
motorcycles = ['honda', 'yamaha', 'suzuki']print(motorcycles)popped_motorcycle = motorcycles.pop()print(motorcycles)print(popped_motorcycle)
pop()也可删除列表中任意位置的元素。
motorcycles = ['honda', 'yamaha', 'suzuki']first_owned = motorcycles.pop(0)print('The first motorcycle I owned was a ' + first_owned.title() + '.')
总结:如果你不确定该使用del 语句还是pop() 方法,下面是一个简单的判断标准:如果你要从列表中删除一个元素,且不再以任何方式使用它,就使用del 语句;如果你要在删除元素后还能继续使用它,就使用方法pop() 。
根据值删除元素
remove()方法可以根据值删除列表中的元素
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']print(motorcycles)motorcycles.remove('ducati')print(motorcycles)
注意:方法remove() 只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来判断是否删除了所有这样的值。
三、组织列表
1.使用方法sort()对列表进行永久性排序
sort()按照字母顺序排序,且是永久性排序
cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort()print(cars)['audi', 'bmw', 'subaru', 'toyota']
如果想要按与字母顺序相反的顺序排列列表元素,可以使用如下方法:
cars = ['bmw', 'audi', 'toyota', 'subaru']cars.sort(reverse=True)print(cars)
2.使用函数sorted()对列表进行临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']print(sorted(cars))
3.倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']print(cars)cars.reverse()print(cars)
4.确定列表长度
cars = ['bmw', 'audi', 'toyota', 'subaru']len(cars)4
5.使用列表时避免索引错误
操作列表
一、遍历列表
magicians = ['alice', 'david', 'carolina']for magician in magicians:print(magician)
二、创建数值列表
1.使用函数range()
for value in range(1,5):print(value)1234
2.使用range()创建数字列表
要创建数字列表,可以使用函数list()将range()的结果直接转换为列表
numbers = list(range(1,6))print(numbers)[1, 2, 3, 4, 5]
even_numbers = list(range(2,11,2))print(even_numbers)
在这个示例中,函数range() 从2开始数,然后不断地加2,直到达到或超过终值(11),因此输出如下:
[2, 4, 6, 8, 10]
3.对数字列表进行简单的统计计算
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]>>> min(digits) 0>>> max(digits) 9>>> sum(digits) 45
4.列表解析
squares = [value**2 for value in range(1,11)]print(squares)
三、使用列表的一部分
1.切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']print(players[0:3])['charles', 'martina', 'michael']
2.遍历切片
players = ['charles', 'martina', 'michael', 'florence', 'eli']print("Here are the first three players on my team:")for player in players[:3]:print(player.title())Here are the first three players on my team:CharlesMartinaMichael
