![](/img/trans.png)
[英]How to sort a group in a way that I get the largest number in the first row and smallest in the second and the second largest in the third and so on
[英]how to get first K smallest number in a dictionary
例如,我有一本字典
dicts["A"] = 1
dicts["B"] = 2
dicts["C"] = 3 # .....etc,
如果我想根據它們的值(即 1 和 2)獲取前 2 個鍵,即"A"
和"B"
,我該怎么辦? 提前致謝。
嘗試:
#lets say
dic={'A':2,'B':1, 'C':5}
#sorting the dict
dic = {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}
現在字典已經排序,遍歷它。 要找到 K 個最小值:
k = K
for i in range(k):
print([k[0] for k in dic.items()][i])
因此,很快:
k = K
for i in range(k):
print([k[0] for k in {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}.items()][i])
作為單線:
k = K
dic={'A':2,'B':1, 'C':5}
print('\n'.join([k[0] for k in {k: v for k, v in sorted(dic.items(), key=lambda item: item[1])}.items()][i] for i in range(k)))
dic={'A':1,'B':2, 'C': 3}
k = 2
[y[0] for y in sorted(dic.items(), key = lambda x: x[1])[:k]]
最后一行根據鍵( x[1]
)對字典項進行排序,然后取前k
個項( [:k]
),然后僅提取鍵( y[0]
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.