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

Jas*_*y.W 7 python list python-3.x

我有5个序列号的列表:

['123', '134', '234', '214', '223'] 
Run Code Online (Sandbox Code Playgroud)

我想获得每个数字的百分比1, 2, 3, 4ith号码中的各个序列的位置.例如,这个数字序列的0th位置上5的数字是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]]
Run Code Online (Sandbox Code Playgroud)

然后期望的结果是返回:

[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]
Run Code Online (Sandbox Code Playgroud)

我到目前为止的尝试:

list(zip(*['123', '134', '234', '214', '223']))
Run Code Online (Sandbox Code Playgroud)

结果:

 [('1', '1', '2', '2', '2'), ('2', '3', '3', '1', '2'), ('3', '4', '4', '4', '3')]
Run Code Online (Sandbox Code Playgroud)

但我被困在这里,然后我不知道如何计算每个数字的元素的百分比1, 2, 3, 4,然后获得所需的结果.任何建议表示赞赏!

Tre*_*vir 0

您可以使用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
Run Code Online (Sandbox Code Playgroud)

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

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

输出:

[[0.4, 0.6, 0.0, 0.0], [0.2, 0.4, 0.4, 0.0], [0.0, 0.0, 0.4, 0.6]]
Run Code Online (Sandbox Code Playgroud)

  • 太多的硬编码。`/5` 应替换为 `/len(x)`,`range(1,5)` 应替换为 `set(''.join(l))` (然后您可以替换 `str( i)` 只包含 `i`)。 (2认同)