简体   繁体   English

如何在列表中添加整数值

[英]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: 对于参数中给定的每个重复数字,我希望它向与其重复的索引加+1,其值从0开始。这是我目前拥有的:

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] 因此,如果我将参数设为mutind等于[0,0,1,2,2,3,3,3]

After running through the for loop, summed_mut should equal [0,1,2,3] 经过for循环后,summed_mut应该等于[0,1,2,3]

I would want the eventual summed_mut to equal [1,0,1,2] 我希望最终的summed_mut等于[1,0,1,2]

Thank You! 谢谢!

Use itertools.groupby 使用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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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