标签:lam fun 如何 ble self als ane 列表 func
作用:就地对列表排序(直接在原列表上做排序)
语法:
list.sort(func=None, key=None, reverse=False)
例子:
>>> arr = [2,8,4,6,9,1,3]
>>> arr.sort()
>>> arr
[1, 2, 3, 4, 6, 8, 9]
作用:对可迭代对象排序,返回一个新的已经排序好的list
差别:
语法:
sorted(iterable, key=None, reverse=False)
例子:
>>> arr = (3,6,7,2,1,4)
>>> sorted(arr)
[1, 2, 3, 4, 6, 7]
参数key:带一个参数的函数(排序时,会依次传入列表的每一项,作为该函数的参数)。该函数用于在比较排序之前进行的操作
例子:
每个字符串比较之前,需要统一小写
>>> test=["A","a","E","W","o"]
>>> test.sort()
>>> test
[‘A‘, ‘E‘, ‘W‘, ‘a‘, ‘o‘]
>>> test.sort(key=lambda x:x.lower())
>>> test
[‘A‘, ‘a‘, ‘E‘, ‘o‘, ‘W‘]
例子:
>>> student_tuples = [
... (‘john‘, ‘A‘, 15),
... (‘jane‘, ‘B‘, 12),
... (‘dave‘, ‘B‘, 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
>>> class Student:
... def __init__(self, name, grade, age):
... self.name = name
... self.grade = grade
... self.age = age
... def __repr__(self):
... return repr((self.name, self.grade, self.age))
>>>
>>> student_objects = [
... Student(‘john‘, ‘A‘, 15),
... Student(‘jane‘, ‘B‘, 12),
... Student(‘dave‘, ‘B‘, 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[(‘dave‘, ‘B‘, 10), (‘jane‘, ‘B‘, 12), (‘john‘, ‘A‘, 15)]
重点来了!
1.多维数组,如何在按照第一个元素排序的基础上,再按第二个关键字进行排序?
>>> arr = [(‘d‘,3),(‘a‘,5),(‘d‘,1),(‘c‘,2),(‘d‘,2)]
>>> sorted(arr, key = lambda x:(x[0],x[1]))
[(‘a‘, 5), (‘c‘, 2), (‘d‘, 1), (‘d‘, 2), (‘d‘, 3)]
2.多维数组,如何实现第一个元素按升序,第二个元素按降序来排列?
>>> arr = [(‘d‘,3),(‘a‘,5),(‘d‘,1),(‘c‘,2),(‘d‘,2)]
>>> sorted(arr, key=lambda x:(x[0], -int(x[1])))
[(‘a‘, 5), (‘c‘, 2), (‘d‘, 3), (‘d‘, 2), (‘d‘, 1)]
sort和sorted深入理解----引子:多维列表,如何实现第一个元素升序,第二个元素降序
标签:lam fun 如何 ble self als ane 列表 func
原文地址:https://www.cnblogs.com/liangmingshen/p/11134553.html