python - 在列表中查找重复值,添加它们并将结果移动到另一个列表

标签 python python-3.x list loops iterator

我有一个列表,我试图找到重复值,将它们添加到临时列表,然后找到重复值的总和,然后将该结果添加到另一个列表。我得到的结果是 [15,6] 以下但我期待得到 [20,12,16]?我似乎无法包含所有重复的数字并让 for 循环包含重复值的最后一个数字。到目前为止,请看一下下面的代码,有什么意见可以帮助吗?

start_list = [5,5,5,5,6,6,8,8]
temp_list = []
final_list = []

for i in range(len(start_list )-1):
    if start_list [i] == start_list [i+1]:
        temp_list.append(start_list [i])
    else:
        total = sum(temp_list)
        final_list .append(total)
        temp_list = []

print(final_list)

最佳答案

只需使用一个计数器:

from collections import Counter

start_list = [5,5,5,5,6,6,8,8]

c = Counter(start_list)
print([x*n for x, n in c.items()])

关于python - 在列表中查找重复值,添加它们并将结果移动到另一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68461119/

相关文章:

python - 数组的分布图

python - 在类和函数内外工作

python - 可以从新进程中的线程访问全局变量吗?

python - 如何在pytorch中求偏导数

python - 为什么将列表初始化为空而不是具有预定大小是 Pythonic 的?

Python numpy 数组 : wrong result when mixing int32 and int8

python-3.x - 如何使多个对象同时工作?

php - 如何干净地制作包含标题和副标题的列表?

python - 如何打印 python 列表,减去特定元素?

python-3.x - 类型错误 : 'generator' object is not subscriptable in python