python 如何排序
原创Python中的排序方法
Python提供了多种排序方法,包括列表对象的sort()方法、sorted()函数以及使用内置函数sorted()和lambda函数进行排序等。
sort()方法用于就地列表排序,而sorted()函数则返回一个新列表,原列表保持不变。
使用sort()方法排序
使用sort()方法可以对列表进行升序或降序排序,默认是升序排序。
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] lst.sort() print(lst) # 输出 [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
如果要进行降序排序,可以指定参数reverse=True:
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] lst.sort(reverse=True) print(lst) # 输出 [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
使用sorted()函数排序
sorted()函数也可以对列表进行升序或降序排序,默认是升序排序。
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] new_lst = sorted(lst) print(new_lst) # 输出 [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
如果要进行降序排序,可以指定参数reverse=True:
lst = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] new_lst = sorted(lst, reverse=True) print(new_lst) # 输出 [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
上一篇:python如何上手 下一篇:python如何gc