2.列表
2.1列表是什么
列表是一系列按特定顺序排列的元素组成。
在Python中,用方括号([])表示列表,并用逗号分隔其中的元素。
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
2.1.1访问列表元素
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])
2.1.2索引从0而不是1开始
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])
print(bicycles[3])
通过将索引指定为-1,可让Python返回最后一个列表元素。
2.1.3使用列表中的各个值
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)
2.2.修改、添加和删除元素
2.2.1修改列表元素
要修改列表元素,可指定列表名和要修改的元素的索引,再指定该元素的新值。
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)
2.2.2在列表中添加元素
1.在列表末尾添加元素append()
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)
2.在列表中插入元素insert()
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.intsert(0,'ducati')
print(motorcycles)
2.2.3从列表中删除元素
1.使用del语句删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
del motorcycles[0]
print(motorcycles)
2.使用方法pop()删除元素
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
poped_motorcycle = motorcycles.pop()
print(motorcycles)
print(poped_motorcycle)
3.弹出列表中任何位置处的元素
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")
总结:删除后不再使用,用del;删除后继续使用,用方法pop()
4.根据值删除元素
motorcycles = ['honda', 'yamaha', 'suzuki','ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)
注意:方法remove()只删除第一个指定的值。如果要删除的值可能在列表中出现多次,就需要使用循环来确保每个值都删除。
2.3组织列表
2.3.1使用方法sort()对列表永久排列,默认按字母顺序
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
按字母顺序相反排列
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)
2.3.2使用函数sorted()对列表临时排序
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\n Here is the original list again:")
print(cars)
如果要按与字母顺序相反的顺序显示列表,也可向函数sorted()传递参数reverse=True
2.3.3倒着打印列表
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)
方法reverse()永久性的修改列表元素的排列顺序,但可随时恢复到原来的排列顺序,只需要对列表再次调用reverse()即可。
2.3.3确定列表长度
cars = ['bmw', 'audi', 'toyota', 'subaru']
len(cars)
2.4使用列表时避免索引错误
需要访问最后一个列表元素时,可使用索引-1
发生索引错误却找不到解决办法时,请尝试将列表或其长度打印出来。
浙公网安备 33010602011771号