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

新手上路,请多包涵

我有这个包含 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 许可协议

阅读 1.4k
2 个回答

您可以使用 count(i) 确定数字 1-4 的出现次数并将其除以 5 以获得百分比:

 sequence=list(zip(*['123', '134', '234', '214', '223']))
percentages=[]
for x in sequence:
    t=list(x)
    temp=[t.count(str(i))/len(x) for i in range(1,5)]  #work out the percentage of each number
    percentages.append(temp) #add percentages to list

或者,作为一个列表理解:

 percentages=[[list(x).count(str(i))/len(x) for i in range(1,5)]for x in sequence]

输出:

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

原文由 Trelzevir 发布,翻译遵循 CC BY-SA 3.0 许可协议

从您的方法开始,您可以使用 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]

原文由 hiro protagonist 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题