1. (按字母顺序排列)——sort()函数
例:
cars =['bmw','audi','toyota','subaru']
cars.sort()
print(cars)
输出得到
['audi', 'bmw', 'subaru', 'toyota']
请点击输入图片描述
2.按字母反序排列——reverse函数
cars =['bmw','audi','toyota','subaru']
cars.sort(reverse=True)# reverse“adj. 反面的颠倒的;n. 倒转,反向”
print(cars)
输出得到
['toyota', 'subaru', 'bmw', 'audi']
请点击输入图片描述
请点击输入图片描述
3.对列表进行临时排序——sorted()函数
cars =['bmw','audi','toyota','subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("Here is the original list again:")
print(cars)
输出得到
Here is the original list:
['bmw', 'audi', 'toyota', 'subaru']
Here is the sorted list:
['audi', 'bmw', 'subaru', 'toyota']
Here is the original list again:
['bmw', 'audi', 'toyota', 'subaru']
请点击输入图片描述
请点击输入图片描述
4. 倒着打印列表——reverse()函数
cars =['bmw','audi','toyota','subaru']
print(cars)
cars.reverse()
print(cars)
输出得到
['bmw', 'audi', 'toyota', 'subaru']
['subaru', 'toyota', 'audi', 'bmw']
请点击输入图片描述
请点击输入图片描述
代码如下:
list = ['banana', 'apple', 'orange', 'blueberry', 'watermelon', 'strawberry', 'mango']
print(list)
list.sort() #根据字母顺序排序
print(list) #['apple', 'banana', 'blueberry', 'mango', 'orange', 'strawberry', 'watermelon']
list.sort(reverse = True) #根据字母相反顺序排序
print(str(list) + "\n") #['watermelon', 'strawberry', 'orange', 'mango', 'blueberry', 'banana', 'apple']
扩展资料
sorted()函数四种重要的特性:
1、sorted()函数不需要定义。它是一个内置函数,可以在标准的Python安装中使用。
2、在没有额外的参数的情况下,sorted()函数按照升序对值进行排列,也就是按照从小到大的顺序。
3、原始的numbers不会改变,因为sorted()函数提供了一个新的有序的输出结果,并且不改变原始值的顺序。
4、当sorted()函数被调用时,它会提供一个有序的列表作为返回值。
最后一点意味着列表可以使用sorted()函数,并且输出结果可以立刻赋值给一个变量。