排序函数sort() 和sorted() 之介绍

一、排序函数sort() 和sorted() 之介绍

今天来讲一下Python中的排序函数。Python中有2个内建的排序函数,分别为sort() 和 sorted()

1.有一个列表 :a=[1,4,5,88,0,7],想要实现排序功能,可以使用sort() 和 sorted()

a=[1,4,5,88,0,7]a.sort()   # 内置方法,没有返回值,默认升序排列
print(a)  # 输出 [0, 1, 4, 5, 7, 88]
a.sort(reverse=True)  #降序排列。默认False:升序;
print(a)   # 输出[88, 7, 5, 4, 1, 0]
b = sorted(a)    # 函数,有返回值,默认升序
print(b)     # [0, 1, 4, 5, 7, 88]
b = sorted(a,reverse=True)  # 有返回值,需要用一个变量来接收
print(b)    # [88, 7, 5, 4, 1, 0]
原文地址:https://www.cnblogs.com/wwbplus/p/11453118.html