我有这个包含 5 个数字序列的列表:
['123', '134', '234', '214', '223']
我想获得每个数字的百分比 1, 2, 3, 4
在每个数字序列的 ith
位置。 For example, the numbers at 0th
position of this 5
sequences of numbers are 1 1 2 2 2
, then I need to calculate the percentage of 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
的每个数字的元素百分比,然后得到想要的结果。任何建议表示赞赏!
原文由 Jassy.W 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
count(i)
确定数字 1-4 的出现次数并将其除以 5 以获得百分比:或者,作为一个列表理解:
输出: