2017-08-26 38 views
0

我正試圖解決問題。這給下面的輸出:如何從python中獲取鍵值?

>>> frequency([13,12,11,13,14,13,7,11,13,14,12,14,14]) 

答:([7], [13, 14])

基本上它返回最高和最低頻率的列表。

我使用collection.Counter()函數所以我有這樣的:

Counter({13: 4, 14: 4, 11: 2, 12: 2, 7: 1}) 

我提取鍵和值,我也得到了在一個列表進行排序我的價值觀。現在我想獲得具有最小和最高值的鍵,以便我可以從中生成列表。

我不知道該怎麼做。

+0

的可能的複製[度日值,快譯通,蟒蛇鑰匙(https://stackoverflow.com/questions/23295315/ get-key-by-value-dict-python) –

回答

2

您可以採取的最大值和最小值,然後再在這些值與列表內涵建立密鑰列表:

c = Counter({13: 4, 14: 4, 11: 2, 12: 2, 7: 1}) 
values = c.values() 
mn, mx = min(values), max(values) 
mins = [k for k, v in c.items() if v == mn] 
maxs = [k for k, v in c.items() if v == mx] 
print (mins, maxs) 
# ([7], [13, 14]) 
+0

謝謝!這工作很好!我也瞭解它! –

1

不是最Python的方式,但容易理解的初學者。

from collections import Counter 
L = [13,12,11,13,14,13,7,11,13,14,12,14,14] 

answer_min = [] 
answer_max = [] 

d = Counter(L) 
min_value = min(d.values()) 
max_value = max(d.values()) 

for k,v in d.items(): 

    if v == min_value: 
     answer_min.append(k) 
    if v == max_value: 
     answer_max.append(k) 

answer = (answer_min, answer_max) 
answer 

給我們([7], [13, 14])。看起來你只需要知道dictionary.items()來解決這個問題。

+0

@ juanpa.arrivillaga沒錯,謝謝。 –

+0

'elif'應該是'if',以處理'min_value'和'max_value'是相同的情況。 –

+0

@MatthiasFripp好的,謝謝。 –

0

你可以試試這個:

import collections 
s = [13,12,11,13,14,13,7,11,13,14,12,14,14] 
count = collections.Counter(s) 
mins = [a for a, b in count.items() if b == min(count.values())] 
maxes = [a for a, b in count.items() if b == max(count.values())] 
final_vals = [mins, maxes] 

輸出:

[[7], [13, 14]] 
+1

我認爲這將重新計算'min(count.values())'列表理解中的每一項,這是不必要的慢。 –

相關問題