我有一个包含单个数值的条目的嵌套列表,我需要确定哪个值的总出现百分比更高。
[['3', '7', '13', '4'],
['7', '3', '2', '1', '13', '4'],
['3', '13'],
['3', '7', '4', '13'],
['7', '3', '13', '4'],
['3', '13', '7', '8', '4'],
['1', '7', '3', '4', '13'],
['13'],
['7', '3', '13'],
['7', '3', '4']]
在此示例中,数字“13”出现在 90% 的条目中。
我知道我可以遍历每个条目,使用计数器并在最后比较结果,但应该有更简洁的方法来执行此操作。
有什么帮助吗?
提前致谢。
最佳答案
怎么样:
items = [['3', '7', '13', '4'],
['7', '3', '2', '1', '13', '4'],
['3', '13'],
['3', '7', '4', '13'],
['7', '3', '13', '4'],
['3', '13', '7', '8', '4'],
['1', '7', '3', '4', '13'],
['13'],
['7', '3', '13'],
['7', '3', '4']]
from collections import Counter
from itertools import chain
print Counter(chain.from_iterable(items)).most_common(1)[0]
# 13, 9
关于Python:返回值在嵌套列表中出现的百分比更高,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19160725/