sorted函數

1、須要用到的函數python

須要用到的函數不多,基本上就是sorted()和lambda。git

sorted()函數原型:算法

sorted(iterable[,key][,reverse])

可見sorted()能夠接受3個參數,須要排序的變量必不可少,而後是key指定排序的元素,reverse指定是否逆序。express

key:一個只有一個參數的函數,這個函數會被用在序列裏的每個元素上,所產生的結果將是排序算法依賴的對比關鍵字。好比說,在對一些字符串排序時,能夠用key=len來實現根據字符串的長度進行排序。這個參數的默認值是恆等函數,也就是默認用元素本身的值來排序 (key=lambda x: x)。函數

lambda實際上就是匿名函數ui

通常形式:spa

lambda arguments: expression

寫成函數形式就是code

def <lambda>(arguments):
    return expression

當lambda和sorted()的key參數結合就有意想不到的效果了。排序

2、各類排序索引

1.簡單list排序

lis = ['a', 'b', 'c']
print(sorted(lis))
# ['a', 'b', 'c']
print(sorted(lis, reverse=True))
# ['c', 'b', 'a']

2.dict的key排序

dic = {'c': 1, 'b': 2, 'a': 3} #字典排序默認按照字典的key排序,返回的也是字典的key
print(sorted(dic))
# ['a', 'b', 'c']
print(sorted(dic, reverse=True))
# ['c', 'b', 'a']

3.dict的value排序

dic = {'c': 1, 'b': 2, 'a': 3}
print(sorted(dic, key=lambda k: dic[k])) #dic([k])就是value
# ['c', 'b', 'a']
print(sorted(dic, key=lambda k: dic[k], reverse=True))
# ['a', 'b', 'c']

4.list內嵌套list排序

lis = [[4, 2, 9], [1, 5, 6], [7, 8, 3]]
print(sorted(lis, key=lambda k: k[0])) #列表內的沒項代入key後的表達式,根據返回值排序
# [[1, 5, 6], [4, 2, 9], [7, 8, 3]]
print(sorted(lis, key=lambda k: k[1]))
# [[4, 2, 9], [1, 5, 6], [7, 8, 3]]
print(sorted(lis, key=lambda k: k[2]))
# [[7, 8, 3], [1, 5, 6], [4, 2, 9]]
print(sorted(lis, key=lambda k: k[0], reverse=True))
# [[7, 8, 3], [4, 2, 9], [1, 5, 6]]

5.dict內嵌套dict排序

dic = {
    'a': {'x': 3, 'y': 2, 'z': 1},
    'b': {'x': 2, 'y': 1, 'z': 3},
    'c': {'x': 1, 'y': 3, 'z': 2},
}
print(sorted(dic, key=lambda k: dic[k]['x']))
# ['c', 'b', 'a']
print(sorted(dic, key=lambda k: dic[k]['y']))
# ['b', 'a', 'c']
print(sorted(dic, key=lambda k: dic[k]['z']))
# ['a', 'c', 'b']
print(sorted(dic, key=lambda k: dic[k]['x'], reverse=True))
# ['a', 'b', 'c']

6.list內嵌套dict排序

lis = [
    {'x': 3, 'y': 2, 'z': 1},
    {'x': 2, 'y': 1, 'z': 3},
    {'x': 1, 'y': 3, 'z': 2},
]
print(sorted(lis, key=lambda k: k['x']))
# [{'z': 2, 'x': 1, 'y': 3}, {'z': 3, 'x': 2, 'y': 1}, {'z': 1, 'x': 3, 'y': 2}]
print(sorted(lis, key=lambda k: k['y']))
# [{'z': 3, 'x': 2, 'y': 1}, {'z': 1, 'x': 3, 'y': 2}, {'z': 2, 'x': 1, 'y': 3}]
print(sorted(lis, key=lambda k: k['z']))
# [{'z': 1, 'x': 3, 'y': 2}, {'z': 2, 'x': 1, 'y': 3}, {'z': 3, 'x': 2, 'y': 1}]
print(sorted(lis, key=lambda k: k['x'], reverse=True))
# [{'z': 1, 'x': 3, 'y': 2}, {'z': 3, 'x': 2, 'y': 1}, {'z': 2, 'x': 1, 'y': 3}]

7.dict內嵌套list排序

dic = {
    'a': [1, 2, 3],
    'b': [2, 1, 3],
    'c': [3, 1, 2],
}
print(sorted(dic, key=lambda k: dic[k][0]))
# ['a', 'b', 'c']
print(sorted(dic, key=lambda k: dic[k][1]))
# ['b', 'c', 'a']
print(sorted(dic, key=lambda k: dic[k][2]))
# ['c', 'b', 'a']
print(sorted(dic, key=lambda k: dic[k][0], reverse=True))
# ['c', 'b', 'a']

實例

一、給定一個只包含大小寫字母,數字的字符串,對其進行排序,保證:

全部的小寫字母在大寫字母前面;
全部的字母在數字前面;
全部的奇數在偶數前面;

>>> s = "Sorting1234"
>>> "".join(sorted(s, key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x)))
'ginortS1324'

二、排序一副FranchDeck。流暢的python書中示例

import collections

Card = collections.namedtuple('Card', ['rank', 'suit']) #命名元組

class FrenchDeck:
    ranks = [str(n) for n in range(2, 11)] + list('JQKA')  #2到10和JQKA
    suits = 'spades diamonds clubs hearts'.split()  #split默認按空格生成列表

    def __init__(self):
        self._cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks] #生成全部52張牌

    def __len__(self):
        return len(self._cards)  #能夠用Len()方法

    def __getitem__(self, position):
        return self._cards[position]  #能夠用索引或切片

suit_values = dict(spades=3, hearts=2, diamonds=1, clubs=0) #設置花色優先級

def spades_high(card):
        rank_value = FrenchDeck.ranks.index(card.rank)  #找到當前Card所在的索引:2的索引爲0
        return rank_value * len(suit_values) + suit_values[card.suit] #返回當前牌對應的優先級數字,若是沒有乘於len(suit_values)那麼('2', 'spades')和('4', 'diamonds')的優先級數字就同樣了,這裏也能夠直接乘於4或5,6....
    
#排序
>>> import Frenchcard
>>> deck = Frenchcard.FrenchDeck()
>>> for i in sorted(deck, key=b.spades_high): #sorted返回一個列表。key後的函數會代入deck列表裏的每一項返回一個優先級數字,並以這個優先級數字排序
...     print(i)
Card(rank='2', suit='clubs')
Card(rank='2', suit='diamonds')
Card(rank='2', suit='hearts')
Card(rank='2', suit='spades')
Card(rank='3', suit='clubs')
Card(rank='3', suit='diamonds')
.............
相關文章
相關標籤/搜索