我有这个包含 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/