排序:sorted()显示临时排序
cars = ['byd','audi','gelly','qirui','chengcheng']
print(sorted(cars))
print(cars)
结果:
['audi', 'byd', 'chengcheng', 'gelly', 'qirui']
['byd', 'audi', 'gelly', 'qirui', 'chengcheng']
sort() 对列表排序并改变原序列
cars = ['byd','audi','gelly','qirui','chengcheng']
print(cars.sort())
print(cars)
结果:
None
['audi', 'byd', 'chengcheng', 'gelly', 'qirui']
注意:cars.sort()不返回结果。
使用sort()方法reverse=True 倒序排列:
cars = ['byd','audi','gelly','qirui','chengcheng']
cars.sort(reverse=True)
print(cars)
结果:
['qirui', 'gelly', 'chengcheng', 'byd', 'audi']
使用sorted()方法reverse=True 倒序排列:
cars = ['byd','audi','gelly','qirui','chengcheng']
print(sorted(cars,reverse=True))
print(cars)
结果:
['qirui', 'gelly', 'chengcheng', 'byd', 'audi']
['byd', 'audi', 'gelly', 'qirui', 'chengcheng']
反转列表(不排序仅反转列表的顺序):reverse()
cars = ['byd','audi','gelly','qirui','chengcheng']
cars.reverse()
print(cars)
结果:
['chengcheng', 'qirui', 'gelly', 'audi', 'byd']
遍历列表:
for循环
cars = ['byd','audi','gelly','qirui','chengcheng']
for car in cars:
print(car)
结果:
byd
audi
gelly
qirui
chengcheng
for循环和enumerate()函数 :
cars = ['byd','audi','gelly','qirui','chengcheng']
for index,car in enumerate(cars):
print(index,car)
结果:
0 byd
1 audi
2 gelly
3 qirui
4 chengcheng
for循环和range()函数
cars = ['byd','audi','gelly','qirui','chengcheng']
for i in range(len(cars)):
print(i,cars[i])
结果:
0 byd
1 audi
2 gelly
3 qirui
4 chengcheng
for循环和iter()函数:
cars = ['byd','audi','gelly','qirui','chengcheng']
for car in iter(cars):
print(car)
结果:
byd
audi
gelly
qirui
chengcheng
while循环:
cars = ['byd','audi','gelly','qirui','chengcheng']
i = 0
while i < len(cars):
print(cars[i])
i +=1
结果:
byd
audi
gelly
qirui
chengcheng
列表合并
加号:
cars = ['byd','audi','gelly','qirui','chengcheng']
planes = ['boyin','shenfei','chengfei']
carsAndPlanes = cars + planes
print(carsAndPlanes)
结果:
['byd', 'audi', 'gelly', 'qirui', 'chengcheng', 'boyin', 'shenfei', 'chengfei']
extend()方法:
cars = ['byd','audi','gelly','qirui','chengcheng']
planes = ['boyin','shenfei','chengfei']
# carsAndPlanes = cars.extend(planes)
cars.extend(planes)
print(cars)
结果:
['byd', 'audi', 'gelly', 'qirui', 'chengcheng', 'boyin', 'shenfei', 'chengfei']
注意:cars.extend(planes)不能返回结果。
使用切片,将一个列表插入另一个列表:
cars = ['byd','audi','gelly','qirui','chengcheng']
planes = ['boyin','shenfei','chengfei']
cars[len(cars):len(cars)]=planes
print(cars)
结果:
['byd', 'audi', 'gelly', 'qirui', 'chengcheng', 'boyin', 'shenfei', 'chengfei']
注意:语法形式如下:
list1[len(list1):len(list1)] = list2
len(list1) 代表将list2插入list1中的位置
标签:qirui,python,cars,chengcheng,列表,gelly,byd,排序,audi From: https://blog.51cto.com/u_16427934/8911374