1 print (‘\n------------3.3.1-永久性排序--------\n‘) 2 cars = [‘bmw‘,‘audi‘,‘toyoto‘,‘subaru‘] 3 # 列表操作的.sort()方法排序,默认为a-z顺序排列,如果按照z-a排列需要传递一个参数‘reverse=True‘ 4 cars.sort() # 永久性按照a-z排序 5 print (cars) 6 cars.sort(reverse=True) # reverse=相反、颠倒、倒序 7 print (cars) 8 9 print (‘\n------------3.3.2-临时排序----------\n‘) 10 11 cars1 = [‘bmw‘,‘audi‘,‘toyoto‘,‘subaru‘] 12 print ("Here is the original list:") # 先显示原始列表一次,original list=原始 列表 13 print (cars1) 14 15 print ("\nHere is the sorted list:") 16 print (sorted(cars1,reverse=True)) # True为a-z 17 print (sorted(cars1,reverse=False)) # False为z-a 18 # 在print中用sorted()函数,使列表临时按照a-z顺序排序,同时,该函数也可以加入参数(reverse=True/false)来进行控制。 19 20 print ("\nHere is the original list again:") 21 print (cars1) # 再次显示原始列表 22 23 print (‘\n------------3.3.3-列表倒序排序------\n‘) 24 25 cars2 = [‘bmw‘,‘audi‘,‘toyoto‘,‘subaru‘] 26 print (cars2) 27 28 cars2.reverse() 29 # 列表操作的.reverse()方法,永久性地反转列表的排列顺序,但可以随时恢复到原来的排列顺序,只需要再次调用.reverse()即可。 30 print (cars2) 31 32 33 print (‘\n------------3.3.4-确定列表长度------\n‘) 34 cars3 = [‘bmw‘,‘audi‘,‘toyoto‘,‘subaru‘,‘benz‘] 35 print (cars3) 36 lenght =len(cars3) # 获取列表长度,即元素的个数,从1开始计数 37 print ("The length of the list is " + str(lenght) + ‘.‘)
------------3.3.1-永久性排序--------
[‘audi‘, ‘bmw‘, ‘subaru‘, ‘toyoto‘]
[‘toyoto‘, ‘subaru‘, ‘bmw‘, ‘audi‘]
------------3.3.2-临时排序----------
Here is the original list:
[‘bmw‘, ‘audi‘, ‘toyoto‘, ‘subaru‘]
Here is the sorted list:
[‘toyoto‘, ‘subaru‘, ‘bmw‘, ‘audi‘]
[‘audi‘, ‘bmw‘, ‘subaru‘, ‘toyoto‘]
Here is the original list again:
[‘bmw‘, ‘audi‘, ‘toyoto‘, ‘subaru‘]
------------3.3.3-列表倒序排序------
[‘bmw‘, ‘audi‘, ‘toyoto‘, ‘subaru‘]
[‘subaru‘, ‘toyoto‘, ‘audi‘, ‘bmw‘]
------------3.3.4-确定列表长度------
[‘bmw‘, ‘audi‘, ‘toyoto‘, ‘subaru‘, ‘benz‘]
The length of the list is 5.
原文地址:https://www.cnblogs.com/hzez/p/10346239.html
时间: 2024-11-07 02:32:08