簡體   English   中英

如何從字典的列表元素中打印出最高值的鍵?

[英]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.

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