PYTHON-排序-sort与sorted区别及应用

list.sort( key=None, reverse=False)
#list就是我们需要排序的列表;
#key:具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。
#reverse :True 降序,False 升序(默认)
def takeSecond(elem):
    print(elem[1])
    return elem[1]
 
# 列表
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
 
# 指定第二个元素排序
random.sort(key=takeSecond)
 
# 输出类别
print ('排序列表:', random)
#output
2 4 1 3 排序列表: [(4, 1), (2, 2), (1, 3), (3, 4)] #就是按照列表里边的元组的第二个元素进行排序

sorted 与 sort的区别:

#sort是在list上的方法,而sorted可以应用在任何可迭代对象;
#sort是在原有列表上操作,sorted是返回一个新的列表
#sorted(iterable, key=None, reverse=False)  
>>> a = [5,2,3,1,4]
>>> a.sort()
>>> a
[1, 2, 3, 4, 5] #在原有列表上操作
>>> a.sorted()
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    a.sorted()
AttributeError: 'list' object has no attribute 'sorted'
>>> sorted([5,2,3,1,4])
[1, 2, 3, 4, 5]#产生一个新列表
>>> 

参考网址:

https://www.runoob.com/python3/python3-func-sorted.html

https://www.runoob.com/python3/python3-att-list-sort.html

猜你喜欢

转载自www.cnblogs.com/xiao-yu-/p/12694094.html
今日推荐