![](/img/trans.png)
[英]How to sort a dictionary to print from highest value to lowest for each key?
[英]How to print the key of highest value from the list's element of the dictionary?
我还是 python 的新手,所以如果我的问题令人困惑,请提前致歉。 我有这个
A : [5, 1, 0, 0, 5, 5, 0]
C : [0, 1, 1, 2, 1, 0, 2]
G : [0, 3, 2, 1, 0, 1, 2]
T : [1, 0, 2, 0, 0, 0, 1]
字典。 我想从列表中打印最高值的键。 例如:- 从列表的第一个元素即 5,0,0,1 A具有我想要打印 A 的最高值,然后是第二个 position 它的G等等。
谢谢你。
编辑: - 嘿伙计们,谢谢你们的所有建议,我能够完成任务。
您可以使用以下内容:
d = {"A": [5, 1, 0, 0, 5, 5, 0],
"C": [0, 1, 1, 2, 1, 0, 2],
"G": [0, 3, 2, 1, 0, 1, 2],
"T": [1, 0, 2, 0, 0, 0, 1]}
maxes = [max(d, key=lambda k: d[k][i]) for i in range(len(list(d.values())[0]))]
# ['A', 'G', 'G', 'C', 'A', 'A', 'C']
假设您的数据在字典中(并且名为d
),您可以尝试:
maxkey = max(d.items(), key=lambda x: max(x[1]))[0]
print(maxkey)
Output:
A
像这样:
>>> def f(di, index):
... max = None
... for key in di:
... if index >= len(di[key]):
... continue
... if max is None or di[max][index] < di[key][index]:
... max = key
... return max
>>> di = {'A': [5, 1, 0, 0, 5, 5, 0],
... 'B': [0, 1, 1, 2, 1, 0, 2]}
>>> f(di, 0)
'A'
>>> f(di, 3)
'B'
对于每个索引(0 到 6),获取在该索引处具有最大值的键。 这可以在列表理解中完成:
[ max(d,key=lambda k:d[k][i]) for i in range(7)]
['A', 'G', 'G', 'C', 'A', 'A', 'C']
如果您的字典中有不同的列表大小,或者您事先不知道列表的长度,您可以先使用最小值 function 获取它:
minLen = min(map(len,d.values()))
maxLetters = [ max(d,key=lambda k:d[k][i]) for i in range(minLen)]
您需要使用 min() 以确保 d[k][i] 不会超出最短列表的大小 go。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.