我製作了一個包含大量數據的字典。我已經繪製了鍵(y軸)與其中的值(x軸)。我在那個陰謀裏有幾個高峯。我想從那個圖中得到這些峯值的鍵和相應的值。如何從一個非常大的字典中獲取最大密鑰
我已經使用這個 進口操作者 MAX(dA.iteritems(),鍵= operator.itemgetter(1))[0]
但它只給我一個最大值。 請幫忙。
我製作了一個包含大量數據的字典。我已經繪製了鍵(y軸)與其中的值(x軸)。我在那個陰謀裏有幾個高峯。我想從那個圖中得到這些峯值的鍵和相應的值。如何從一個非常大的字典中獲取最大密鑰
我已經使用這個 進口操作者 MAX(dA.iteritems(),鍵= operator.itemgetter(1))[0]
但它只給我一個最大值。 請幫忙。
爲了獲得最大價值的所有實例,使用此代碼:
a=max(dA.iteritems(), key = operator.itemgetter(1)) #finds the max value
print [b for b in dA.keys() if dA[b]==a[1]]
#the above line iterates through the keys of dA and returns all
#x values where the y associated with that x is equal to a[1], the max value.
但是,你需要找到的峯值。你要做的就是:
a=dA.items()
result=[] #we will store the answer in here
for i in range(1, len(a)):
if a[i-1][1]<a[i][1] and a[i][1]>a[i+1][1]: #if there is a peak
result.append(a[i]) #add the x-value and the y-value to the list
print result
試試這個:
import operator
def dict_top_n_subset(d, n):
"""Given a dict d, return a subset dict with the top n value"""
n = min(n, len(d))
return dict(sorted(d.iteritems(), key=operator.itemgetter(1))[-n:])
使用例:
>>> d={1:5, 2:10, 3:7, 4:73, 5:6}
>>> dict_top_n_subset(d, 1)
{4: 73}
>>> dict_top_n_subset(d, 2)
{2: 10, 4: 73}
>>> dict_top_n_subset(d, 3)
{2: 10, 3: 7, 4: 73}
請記住,這可能會使用大量內存(2個?),如果你的字典中巨大的,在這種情況下,您可能需要手動迭代並跟蹤自己的峯值 - 但這比2行代碼困難得多。
import heapq
import operator
dict(heapq.nlargest(n, data_dict.iteritems(), key=operator.itemgetter(1)))
使用heapq.nlargest
高效地找到n
最高鍵值對,按值排序。