【发布时间】:2021-07-26 06:50:32
【问题描述】:
这样的列表:
[1,1,1,2,2,3,3,3]
我想得到每个唯一数字[1,2,3] 的总和,即[3, 4, 9]。使用相关帖子How to get unique values with respective occurrence count from a list in Python? 中的一种方法,我可以使用以下方法获取每个唯一编号的出现计数:
L = [1,1,1,2,2,3,3,3]
uniq, counts = np.unique(L, return_counts=True)
counts
它给出了输出[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)
这给出了所需的输出[3, 4, 9]。有谁知道是否可以更优雅地做同样的事情?
【问题讨论】:
-
我会使用 collections.Counter。
标签: python