python列表排序不同方法
1.使用列表处理函数:(这是最简单也是常用的一种方法)
ls.sort()
sorted(ls)
相同点:两个函数都有可选参数reserve,默认reverse=False从小到大排序,当reverse=True时从大到小排序
区别:ls.sort()是列表的函数,而sorted是内置函数,操作对象为iterable对象,sorted的使用范围比sort更广。其次ls.sort()更新原列表,不返回新的列表,sorted()返回一个新的列表。
案例:
ls=[12,34,23,8,39,78]
ls.sort()
print(ls)
[8, 12, 23, 34, 39, 78]
ls=[12,34,23,8,39,78]
sorted(ls)
[8, 12, 23, 34, 39, 78]
ls
[12, 34, 23, 8, 39, 78]
sorted(ls,reverse=True)
[78, 39, 34, 23, 12, 8]
2.使用小技巧函数min()
def converse(ls):
a=len(ls)
lt=[]
for i in range(a):
lt.append(min(ls))
ls.remove(min(ls))
print(lt)
ls=[12,34,23,8,39,78]
converse(ls)
[8, 12, 23, 34, 39, 78]
3.冒泡排序法
原理:一组数据相邻的数据依次比较,如果前一个数大于后一个数就交换他们的位置,每一趟排序都会产生一个确定位置的数字。对于含有N 个数字的列表,需要进行N-1趟排序。下面这个例子较为直观:
def converse(ls):
for i in range(len(ls)):
for j in range(len(ls)-i-1):
if ls[j] >=ls[j + 1]:
ls[j], ls[j + 1] = ls[j + 1], ls[j]
print(ls)
converse([8,7,6,5,4,3,2,1])
[7, 6, 5, 4, 3, 2, 1, 8]
[6, 5, 4, 3, 2, 1, 7, 8]
[5, 4, 3, 2, 1, 6, 7, 8]
[4, 3, 2, 1, 5, 6, 7, 8]
[3, 2, 1, 4, 5, 6, 7, 8]
[2, 1, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]
def converse(ls):
for i in range(len(ls)):
for j in range(len(ls)-i-1):
if ls[j] >=ls[j + 1]:
ls[j], ls[j + 1] = ls[j + 1], ls[j]
print(ls)
converse([8,7,6,5,4,3,2,1])
[1, 2, 3, 4, 5, 6, 7, 8]