简体   繁体   中英

How do I add to the value of integers in a list

I have this program that I want to take the list I give it as an argument, then add those numbers in a new list one time. For every duplicate number that is given in the argument I want it to add +1 to the indices that it is a duplicate of with the value starting at 0. This is what I currently have:

def mut_sum(mutind):
    summed_mut=[]
    for i in mutind:
        if i not in summed_mut:
            summed_mut.append(i)
        else:

So if I give the argument as mutind equals [0,0,1,2,2,3,3,3]

After running through the for loop, summed_mut should equal [0,1,2,3]

I would want the eventual summed_mut to equal [1,0,1,2]

Thank You!

Use itertools.groupby

Works like this:

from itertools import groupby

mutind = [0,0,1,2,2,3,3,3]
vals = [(x, len(list(y))) for x, y in groupby(mutind)]
# vals now contains the values of the unique items and the count of each items
[x for x, _ in vals]
# [0, 1, 2, 3]
[y - 1 for _, y in vals]
# [1, 0, 1, 2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM