对列表元素进行排序
- 使用方法sort()对列表进行永久性排序,如fruits.sort()
- 使用函数sorted ()对列表进行临时排序,如sorted(fruits)
详细例子如下:
1. 使用方法sort()对列表进行永久性排序
fruits =["apples", "pear", "orange", "cherry"]
fruits.sort()
print(fruits)
fruits.sort(reverse=True) //与字母相反的顺序打印列表
print(fruits)
// 输出结果为
['apples', 'cherry', 'orange', 'pear']
['pear', 'orange', 'cherry', 'apples']
2. 使用函数sorted ()对列表进行临时排序
fruits =["apples", "pear", "orange", "cherry"]
print(sorted(fruits))
print(sorted(fruits,reverse=True)) //与字母顺序相反的顺序打印列表
print(fruits)
输出结果为:
['apples', 'cherry', 'orange', 'pear']
['pear', 'orange', 'cherry', 'apples']
['apples', 'pear', 'orange', 'cherry']