Python基础知识学习_列表增、修、删、排序、长度操作
1、列表的修改、添加、删除操作
1.1 修改列表元素
bicycles = ['trek','cannonda','redline','specialized']
print(bicycles) # 打印列表
bicycles[0] = "ducati" # 可通过下标修改所有的元素
print(bicycles)
结果显示:
['trek', 'cannonda', 'redline', 'specialized']
['ducati', 'cannonda', 'redline', 'specialized']
1.2 在列表中添加元素
1.2.1 在列表尾部添加元素( .append())
motorcycles = ["honda","yamaha","suzuki"]
print(motorcycles)
# 尾部添加元素
motorcycles.append('ducati')
print(motorcycles)
结果显示:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha', 'suzuki', 'ducati']
1.2.2 在列表任何位置添加元素( .insert(index,elem))
motorcycles = ["honda","yamaha","suzuki"]
print(motorcycles)
# 1 的位置添加元素
motorcycles.insert(1, 'ducati')
print(motorcycles)
结果显示:
['honda', 'yamaha', 'suzuki']
['honda', 'ducati', 'yamaha', 'suzuki']
注意:列表是单端数组,在尾部添加数据比在任何位置添加数据要快
duque容器是双端数组,可以在队头和队尾添加数据
2、从列表中删除元素(位置或值)
2.1 del 加 元素位置删除
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
del motorcycles[0] # 删除下标为0位置的元素
print(motorcycles)
结果显示:
['honda', 'yamaha', 'suzuki']
['yamaha', 'suzuki']
2.2 pop() 方法删除列表尾部元素或其他位置的元素(使用index)
作用:pop()方法可以将移除的的值赋值给另一个变量来使用
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
poped_motorcycle = motorcycles.pop() # 删除最后一个位置的元素
print(motorcycles)
poped_motorcycle1 = motorcycles.pop(1) # 删除index = 1 位置处的元素
print(motorcycles)
结果显示
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
['honda']
2.3 remove() 方法,根据值来删除元素
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
motorcycles.remove('suzuki')
print(motorcycles)
结果显示:
['honda', 'yamaha', 'suzuki']
['honda', 'yamaha']
例子:结合字符串拼接技术
motorcycles = ['honda','yamaha','suzuki']
print(motorcycles)
too_expensive = 'suzuki'
motorcycles.remove(too_expensive)
print("\nA " + too_expensive.title() + "is too expensive for me.")
结果显示:
['honda', 'yamaha', 'suzuki']
A Suzukiis too expensive for me.
注意:remove只能删除集和中的第一次出现的值,
如果还要删除相同的值,需要结合for循环
3、组织列表(排序、反转、计算列表长度)
3.1 排序(sort()对列表进行永久性排序)
cars = ['cars','dudi','toyota','subaru']
cars.sort()
print(cars)
结果显示:
['cars', 'dudi', 'subaru', 'toyota']
3.2 使用函数sorted()对列表进行临时排序
保留列表元素原来的排列顺序,同时以特定的顺序呈现他们
sorted: 按特定顺序显示列表,不影响他们在列表中的原始列表排列顺序
cars = ['cars','dudi','toyota','subaru']
print("Here is the original list: ")
print(cars)
print("\nHere is the sorted list: ")
print(sorted(cars)) # 按与字母相同顺序排序
print(sorted(cars,reverse=True)) # reverse 按与字母相反顺序排序
结果显示:
Here is the original list:
['cars', 'dudi', 'toyota', 'subaru']
Here is the sorted list:
['cars', 'dudi', 'subaru', 'toyota']
['toyota', 'subaru', 'dudi', 'cars']
3.3 倒着打印列表 - reverse()
reverse()永久性地修改列表元素的排列顺序,也可以随时恢复到原始顺序
cars = ['bmw','audi','toyota','subaru']
print(cars)
cars.reverse() # 倒序
print(cars)
cars.reverse() # 顺序
print(cars)
结果显示:
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
['bmw', 'audi', 'toyota', 'subaru']
3.4 确定列表的长度(len())
cars = ['bmw','audi','toyota','subaru']
len_cars = len(cars)
print(len_cars)
结果显示:
4