2017-08-26 103 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())'列表理解中的每一项,这是不必要的慢。 –