索引 -1 返回列表最后一个元素,-2 返回倒数第二个列表元素,依次类推。
在列表中添加元素
在末尾添加元素 - append
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles) # ['honda', 'yamaha', 'suzuki', 'ducati']
在列表中插入元素 - insert
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles) # ['ducati', 'honda', 'yamaha', 'suzuki']
从列表中删除元素
根据索引删除元素
del
使用 del
可删除列表中具体索引位置的元素。
motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles) # ['yamaha', 'suzuki']
pop
pop()
弹出列表中最后一个元素并返回该元素。可以通过传入索引,弹出索引位置处的元素。
motorcycles = ['honda', 'yamaha', 'suzuki']
last_owned = motorcycles.pop()
print(motorcycles) # ['honda', 'yamaha']
print(last_owned) # suzuki
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(motorcycles) # ['yamaha', 'suzuki']
print(first_owned) # honda
根据值删除元素
remove
remove()
删除列表中第一个指定的值。
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.remove('honda')
print(motorcycles) # ['yamaha', 'suzuki']
motorcycles = ['honda', 'yamaha', 'suzuki', 'honda']
motorcycles.remove('honda')
# 只删除了第一个
print(motorcycles) # ['yamaha', 'suzuki', 'honda']
组织列表
使用 sort() 对列表永久排序
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.sort()
print(motorcycles) # ['honda', 'suzuki', 'yamaha']
传入 reverse=True
可以倒序排列
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.sort(reverse = True)
print(motorcycles) # ['yamaha', 'suzuki', 'honda']
使用 sorted() 对列表临时排序
motorcycles = ['honda', 'yamaha', 'suzuki']
print(sorted(motorcycles)) # ['honda', 'suzuki', 'yamaha']
print(motorcycles) # ['honda', 'yamaha', 'suzuki']
可以传入 reverse=True
作为 sorted()
第二个参数对列表进行临时倒序排序
motorcycles = ['honda', 'yamaha', 'suzuki']
print(sorted(motorcycles, reverse = True)) # ['yamaha', 'suzuki', 'honda']
print(motorcycles) # ['honda', 'yamaha', 'suzuki']
使用 reverse() 倒着打印列表
motorcycles = ['bmw', 'audi', 'toyota', 'subaru']
motorcycles.reverse()
print(motorcycles) # ['subaru', 'toyota', 'audi', 'bmw']
使用 len() 确定列表长度
motorcycles = ['bmw', 'audi', 'toyota', 'subaru']
print(len(motorcycles)) # 4