这是我的字典:
d = {'G': ['R'],
'L': ['H'],
'H': ['H', 'L', 'T', 'M'],
'T': ['R'],
'S': ['M', 'L', 'H'],
'M': ['R']}
我想从列表中找到该词典中最常用的值。跳跃以获得输出:
['H', 'R']
这是我尝试运行的代码:
values_list = list(d.values())
max(set(values_list), key=values_list.count)
运行此代码时,我收到错误“无法散列的类型:'列表'”。我想知道是否有一个简单的代码可以解决我的问题。
答案 0 :(得分:0)
尝试:
import collections
import itertools
values = [[x] if isinstance(x, str) else x for x in d.values()]
counter = collections.Counter(itertools.chain.from_iterable(values))
max_value = max(counter.values()) # maximum value
max_keys = [k for k, v in counter.items() if v == max_value] # getting all keys containing the `maximum`
print(max_keys)
计数器:
Counter({'R': 3, 'H': 3, 'L': 2, 'T': 1, 'M': 2})
最大键数:
['R', 'H']
OR
from functools import reduce
from collections import Counter
values_list = list(d.values())
li = reduce(lambda x,y: x+y,values_list)
counter = Counter(li)
m = max(counter.values())
r = [k for k in counter if counter[k] == m]
r:
['R', 'H']