Find duplicate values in list, add them and move the result to another list

Viewed 135

I have a list that I'm trying to find duplicate values, add them to a temp list, then find the sum of the duplicate values, and then add that result to another list. The result I get is [15,6] for the following but I was expecting to get [20,12,16]? I cant seem to include all the duplicate numbers and to get the for loop to include the last number of the duplicated value. Please take a look at the following code so far, any comments would help?

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)
2 Answers

Just use a counter:

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()])

from collections import Counter

test=[5,5,5,5,6,6,8,8,8]
test1=Counter(test);
test2=[]

for i in test1: 
    if i==5:
        test1[i]=i*4
        test2.append(test1[i])
    elif i==6:
        test1[i]=i*2
        test2.append(test1[i])
    else:
        test1[i]=i*2
        test2.append(test1[i])
print(test1) 
print(test2)       
Related