如何从 Python 中的列表中获取具有相应出现次数的唯一值的总和?

ves*_*and 5 python

有这样的列表:

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

我想获得每一个唯一的数字的总和[1,2,3][3, 4, 9]。使用相关帖子中的方法如何从 Python 中的列表中获取具有相应出现次数的唯一值?我能够使用以下方法获得每个唯一编号的出现次数:

L = [1,1,1,2,2,3,3,3]
uniq, counts = np.unique(L, return_counts=True)
counts
Run Code Online (Sandbox Code Playgroud)

这给出了输出[3, 2, 3]。有了这个,我就可以使用带有枚举For Loop和一些相当神秘的条件的繁琐方法来获得我正在寻找的东西:

L = [1,1,1,2,2,3,3,3]
elements = [3,2,3]
    
sums = []
index = 0
for i, e in enumerate(elements):
    if i == 0:
        sums.append(sum(L[0:e]))
        index = index + e
    else:
        sums.append(sum(L[index:index + e]))
        index = index + e
print(sums)
Run Code Online (Sandbox Code Playgroud)

这给出了所需的输出[3, 4, 9]。有谁知道是否可以更优雅地做同样的事情?

Mar*_*yer 6

由于您使用的是 Numpy,您可以将已有的结果相乘np.unique

import numpy as np

L = [1,1,1,2,2,3,3,3]    
uniq, counts = np.unique(L, return_counts=True)

uniq * counts
# array([3, 4, 9])
Run Code Online (Sandbox Code Playgroud)