sorted 用于对集合进行排序(这里集合是对可迭代对象的一个统称,他们可以是列表、字典、set、甚至是字符串),它的功能非常强大。
list = [1,5,7,2,4]
sorted(list)
Out[87]: [1, 2, 4, 5, 7]
#可以设定时候排序方式,默认从小到大,设定reverse = False 可以从大到小
sorted(list,reverse=False)
Out[88]: [1, 2, 4, 5, 7]
sorted(list,reverse=True)
Out[89]: [7, 5, 4, 2, 1]
# 使用key,默认搭配lambda函数使用
sorted(chars,key=lambda x:len(x))
Out[92]: ['a', 'is', 'boy', 'bruce', 'handsome']
sorted(chars,key=lambda x:len(x),reverse= True)
Out[93]: ['handsome', 'bruce', 'boy', 'is', 'a']
tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
#key=lambda x: x[1]中可以任意选定x中可选的位置进行排序
sorted(tuple_list, key=lambda x: x[1])
Out[94]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
sorted(tuple_list, key=lambda x: x[0])
Out[95]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]
sorted(tuple_list, key=lambda x: x[2])
Out[96]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]
class tuple_list:
def __init__(self, one, two, three):
self.one = one
self.two = two
self.three = three
def __repr__(self):
return repr((self.one, self.two, self.three))
tuple_list_ = [tuple_list('A', 1,5), tuple_list('B', 3,2), tuple_list('C', 2,6)]
sorted(tuple_list_, key=lambda x: x.one)
Out[104]: [('A', 1, 5), ('B', 3, 2), ('C', 2, 6)]
sorted(tuple_list_, key=lambda x: x.two)
Out[105]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
sorted(tuple_list_, key=lambda x: x.three)
Out[106]: [('B', 3, 2), ('A', 1, 5), ('C', 2, 6)]
class tuple_list:
def __init__(self, one, two, three):
self.one = one
self.two = two
self.three = three
def __repr__(self):
return repr((self.one, self.two, self.three))
tuple_list_ = [tuple_list('C', 1,5), tuple_list('A', 3,2), tuple_list('C', 2,6)]
# 首先根据one的位置来排序,然后根据two的位置来排序
sorted(tuple_list_, key=lambda x:(x.one, x.two))
Out[112]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]
tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]
class tuple_list_class:
def __init__(self, one, two, three):
self.one = one
self.two = two
self.three = three
def __repr__(self):
return repr((self.one, self.two, self.three))
tuple_list_ = [tuple_list_class('C', 1,5), tuple_list_class('A', 3,2), tuple_list_class('C', 2,6)]
from operator import itemgetter
sorted(tuple_list, key=itemgetter(1))
Out[119]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]
from operator import attrgetter
sorted(tuple_list_, key=attrgetter('one')) # attrgetter 传入的参数必须是str
Out[120]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]
# 如果是根据多个类的参数排序,按照参数定义顺序
from operator import attrgetter
sorted(tuple_list_, key=attrgetter('two','one'))
Out[121]: [('C', 1, 5), ('C', 2, 6), ('A', 3, 2)]