Python列表排序方法详解:从小到大、从大到小、自定义排序(python)

一、从小到大排序

Python列表提供了多种方法实现从小到大排序,最常用的方法包括:

1、使用sort()方法

list1 = [4,2,1,3]
list1.sort()
print(list1)

上述代码的输出结果为[1, 2, 3, 4],sort()方法会改变原列表。

2、使用sorted()函数

list1 = [4,2,1,3]
sorted_list = sorted(list1)
print(sorted_list)

上述代码的输出结果为[1, 2, 3, 4],sorted()函数会返回一个新的列表。

二、从大到小排序

从大到小排序与从小到大排序类似,只需对列表进行从小到大排序后再进行反转即可。

1、使用sort()方法

list1 = [4,2,1,3]
list1.sort(reverse=True)
print(list1)

上述代码的输出结果为[4, 3, 2, 1],sort()方法会改变原列表。

2、使用sorted()函数

list1 = [4,2,1,3]
reverse_sorted_list = sorted(list1, reverse=True)
print(reverse_sorted_list)

上述代码的输出结果为[4, 3, 2, 1],sorted()函数会返回一个新的列表。

三、自定义排序

有时候我们需要按照自己的规则进行排序,这时可以使用sort()方法或sorted()函数提供的key参数。

1、使用sort()方法

list1 = ['apple','banana','Cherry','dates']
list1.sort(key=str.lower)
print(list1)

上述代码的输出结果为[‘apple’, ‘banana’, ‘Cherry’, ‘dates’],sort()方法会改变原列表。key参数指定了按照小写字母进行排序。

2、使用sorted()函数

list1 = ['apple','banana','Cherry','dates']
sorted_list = sorted(list1, key=str.lower)
print(sorted_list)

上述代码的输出结果为[‘apple’, ‘banana’, ‘Cherry’, ‘dates’],sorted()函数会返回一个新的列表。key参数指定了按照小写字母进行排序。

四、总结

Python列表提供了多种排序方法,从小到大、从大到小、自定义排序都可以轻松实现。根据具体需求选择排序方法并使用对应的函数或方法即可。

Published by

风君子

独自遨游何稽首 揭天掀地慰生平