Python:返回值在嵌套列表中出现的百分比更高

标签 python

我有一个包含单个数值的条目的嵌套列表,我需要确定哪个值的总出现百分比更高。

[['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/

相关文章:

python - 从被调用函数捕获异常

python - 如何为 Python matplotlib.animation 添加随时间变化的标题?

Python argparse - 禁用子命令的帮助?

python - pynvrtc 在 Google Colab : libnvrtc. 上找不到

python - 范围作为Python中的字典键

python - 使用 SWIG 绑定(bind) Python/C++ 模板

python - 使用 gridsearchcv 进行逻辑回归的特征重要性

python - 设置 pandas 中 x 轴位置的简单方法?

python - 如何 "unfinalize"图表?

python - 如何检测哪些圆圈被填充 + OpenCV + Python