sorted 用于對集合進(jìn)行排序(這里集合是對可迭代對象的一個(gè)統(tǒng)稱,他們可以是列表、字典、set、甚至是字符串),它的功能非常強(qiáng)大
1、對列表排序,返回的對象不會改變原列表
list = [1,5,7,2,4]sorted(list)Out[87]: [1, 2, 4, 5, 7]#可以設(shè)定時(shí)候排序方式,默認(rèn)從小到大,設(shè)定reverse = False 可以從大到小sorted(list,reverse=False)Out[88]: [1, 2, 4, 5, 7]sorted(list,reverse=True)Out[89]: [7, 5, 4, 2, 1]
2、根據(jù)自定義規(guī)則來排序,使用參數(shù):key
# 使用key,默認(rèn)搭配lambda函數(shù)使用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']
3、根據(jù)自定義規(guī)則來排序,對元組構(gòu)成的列表進(jìn)行排序
tuple_list = [('A', 1,5), ('B', 3,2), ('C', 2,6)]#key=lambda x: x[1]中可以任意選定x中可選的位置進(jìn)行排序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)]
4、排序的元素是自定義類
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)]
5、sorted 也可以根據(jù)多個(gè)字段來排序
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)]# 首先根據(jù)one的位置來排序,然后根據(jù)two的位置來排序sorted(tuple_list_, key=lambda x:(x.one, x.two))Out[112]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]
6、使用operator 中的itemgetter方法和attrgetter方法
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 itemgettersorted(tuple_list, key=itemgetter(1))Out[119]: [('A', 1, 5), ('C', 2, 6), ('B', 3, 2)]from operator import attrgettersorted(tuple_list_, key=attrgetter('one')) # attrgetter 傳入的參數(shù)必須是strOut[120]: [('A', 3, 2), ('C', 1, 5), ('C', 2, 6)]# 如果是根據(jù)多個(gè)類的參數(shù)排序,按照參數(shù)定義順序from operator import attrgettersorted(tuple_list_, key=attrgetter('two','one'))Out[121]: [('C', 1, 5), ('C', 2, 6), ('A', 3, 2)]
新聞熱點(diǎn)
疑難解答
圖片精選