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

2024-04-24 07:38:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有5个数字序列的列表:

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

我想得到每个数在每个数列的ith位置上的百分比。例如,这个5序列的0th位置的数字是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数中元素的百分比,然后得到想要的结果。任何建议都很感激!


Tags: ofthe元素列表position序列数字zip
3条回答

从您的方法开始,您可以使用^{}

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]

您可以像创建压缩列表一样开始:

zipped = zip(*l)

然后将itertools.Counter映射到它,以便从zip中获取结果中每个项的计数:

counts = map(Counter, zipped)

然后再看一遍,根据他们的数量除以他们的大小创建一个列表:

res = [[c[i]/sum(c.values()) for i in '1234'] for c in counts]
print(res) 
[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]

如果你是一个单行本的人,把理解中的前两个写进一行:

res = [[c[i]/sum(c.values()) for i in '1234'] for c in map(Counter, zip(*l))]

此外,如注释中所述,如果您不提前知道元素,sorted(set(''.join(l)))可以替换'1234'

您可以使用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]]

相关问题 更多 >