python - 如何计算列表中每个元素的百分比?

标签 python list python-3.x

我有这个包含 5 个数字序列的列表:

['123', '134', '234', '214', '223'] 

并且我想获取每个数字序列的第 位置的每个数字 1, 2, 3, 4 的百分比。比如这个5数列在第0位置的数是1 1 2 2 2,那么我需要计算 1, 2, 3, 4 在此数字序列中,并将百分比作为新列表的 0th 元素返回。

['123', '134', '234', '214', '223']

0th position: 1 1 2 2 2   the percentage of 1,2,3,4 are respectively: [0.4, 0.6, 0.0, 0.0]

1th position: 2 3 3 1 2   the percentage of 1,2,3,4 are respectively: [0.2, 0.4, 0.4, 0.0]

2th position: 3 4 4 4 3   the percentage of 1,2,3,4 are respectively: [0.0, 0.0, 0.4, 0.6]]

然后期望的结果是返回:

[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]

到目前为止我的尝试:

list(zip(*['123', '134', '234', '214', '223']))

结果:

 [('1', '1', '2', '2', '2'), ('2', '3', '3', '1', '2'), ('3', '4', '4', '4', '3')]

但是卡在这里,不知道如何计算1, 2, 3, 4每个数字的元素所占的百分比,然后得到想要的结果。任何建议表示赞赏!

最佳答案

从您的方法开始,您可以使用 Counter 完成剩下的工作

from collections import Counter

for item in zip(*['123', '134', '234', '214', '223']):
    c = Counter(item)
    total = sum(c.values())
    percent = {key: value/total for key, value in c.items()}
    print(percent)

    # convert to list
    percent_list = [percent.get(str(i), 0.0) for i in range(5)]
    print(percent_list)

打印

{'2': 0.6, '1': 0.4}
[0.0, 0.4, 0.6, 0.0, 0.0]
{'2': 0.4, '3': 0.4, '1': 0.2}
[0.0, 0.2, 0.4, 0.4, 0.0]
{'4': 0.6, '3': 0.4}
[0.0, 0.0, 0.0, 0.4, 0.6]

关于python - 如何计算列表中每个元素的百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41450394/

相关文章:

python - terraform 可以为多个基础设施/工作空间并行运行 "apply"吗?

python - 使用带有 np.array 值的字典列表创建 DataFrame

python - 如果它不以 http 开头,我如何将 http 添加到 url?

c# - 维护内存的可重用列表

javascript - Knockout 可观察数组不会重新呈现我的列表

R——未列出时将其他元素强制转换为字符

python - 值错误 : operands could not be broadcast together with shapes in Naive bayes classifier

python-3.x - 为 Pandas 中的每个组填充缺失的日期和回填值

python - 从另一个 python 文件控制 python 进程

python - Tkinter。在输入框中按 Enter。附加到文本框。如何?