簡體   English   中英

按值對字典排序,然后如果按鍵相等

[英]sort dict by value then if equal by keys

我創建了一個字典,鍵=列表值中的單詞=它們的計數。 想要按計數(值)對它們進行排序,那么如果計數相等,則按 alpha(鍵)對它們進行排序

a = [to, be, or, not, to, be, ae, ae]
w={}
for i in a:
    w[i]=a.count(i)
e=dict(sorted(w.items(),key= lambda a: (a[1],a[0]),reverse=True))
for i, k in e.items():
    print(i , k)

我現在得到的是

to 2
be 2
ae 2
or 1
not 1

我想要的是

ae 2
be 2
to 2
not 1
or 1 

我是菜鳥

reverse=true適用於元組的兩個元素。 這就是為什么您的字母數字 output 是倒退的。

要反轉元組的第一個元素的順序而不是另一個元素的順序,您可以否定數字:

sorted(w.items(),key= lambda a: (-a[1],a[0]))

如果您遇到需要對具有不同 ASC/DESC 順序的多個元組元素和不容易否定的元素(如整數)進行排序的問題,您可以使用以下技術。

https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts multisort排序

由於排序是穩定的,因此以下將起作用:

def multisort(xs, specs):
     for i, reverse in reversed(specs):
         xs.sort(key=lambda x: x[i], reverse=reverse)
     return xs

items = [('to', 2), ('be', 2), ('or', 1), ('not', 1), ('ae', 2)]
multisort(items, [(0, False), (1, True)])

Output:

[('ae', 2), ('be', 2), ('to', 2), ('not', 1), ('or', 1)]

問題是reverse關鍵字對於你想要的來說太生硬了: sorted元組排序,然后反轉結果。 您只想按 integer 進行反向排序。 幸運的是,您可以通過簡單地否定每個 integer 來做到這一點。 (這個技巧顯然不適用於任意值。)

e = dict(sorted(w.items(), key=lambda a: (-a[1], a[0])))

一般來說,你可以自己寫比較function:

# 1 means x < y
# -1 means x > y
# 0 means x == y
def compare(x, y):
    if x[1] < y[1]:
        return 1
    elif x[1] > y[1]:
        return -1
    elif x[0] < y[0]:
        return -1
    elif x[0] > y[0]:
        return 1
    else:
        return 0
       

然后使用( functools.cmp_to_key )[https://docs.python.org/3/library/functools.html#functools.cmp_to_key]:

from functools import cmp_to_key

e = dict(sorted(w.items(), key=cmp_to_key(compare)))

我會使用自定義sorted keycollections.Counter實例!

from collections import Counter

a = ['to', 'be', 'or', 'not', 'to', 'be', 'ae', 'ae']

for word, count in sorted(
    Counter(a).items(), key=lambda c: (-c[1], c[0])
):
    print(word, count)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM