Python - 元素在列表中出现的最大次数

时间:2018-01-19 13:43:09

标签: python python-3.x

鉴于以下列表my_list = [ ['red', 'yellow', 'green'], ['red', 'yellow', 'green'], ['red', 'green', 'red']],我想找到最多出现的元素。我已经实现了一个蛮力的mathod以及一个新的列表和一个字典来保存每个元素的值,但效率并不令人满意。哪个是实现此搜索的最佳方式?我使用的是Python 3.

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