鉴于以下列表my_list = [ ['red', 'yellow', 'green'], ['red', 'yellow', 'green'], ['red', 'green', 'red']]
,我想找到最多出现的元素。我已经实现了一个蛮力的mathod以及一个新的列表和一个字典来保存每个元素的值,但效率并不令人满意。哪个是实现此搜索的最佳方式?我使用的是Python 3.
答案 0 :(得分:2)
my_list = [ ['red', 'yellow', 'green'], ['red', 'yellow', 'green'], ['red', 'green', 'red']]
new_list = [k for v in my_list for k in v]
from collections import Counter
c = Counter(new_list)
print c.most_common(1)
>>> [('red', 4)]
答案 1 :(得分:0)
您可以展平嵌套列表并应用max
函数:
my_list = [ ['red', 'yellow', 'green'], ['red', 'yellow', 'green'], ['red', 'green', 'red']]
new_list = [i for x in my_list for i in x]
max_val = max(new_list, key=lambda x:new_list.count(x))
输出:
'red'
答案 2 :(得分:0)
您可以使用itertools.chain.from_iterable
展平您的列表,然后使用collections.defaultdict
存储计数,并从那里轻松获取最大密钥:
from collections import defaultdict
from operator import itemgetter
from itertools import chain
my_list = [['red', 'yellow', 'green'], ['red', 'yellow', 'green'], ['red', 'green', 'red']]
d = defaultdict(int)
for word in chain.from_iterable(my_list):
d[word] += 1
print(max(d.items(), key = itemgetter(1))[0])
# red