用Python替换列表中的重复元素?

时间:2015-02-22 18:08:39

标签: python list

例如,如果我有一个如下列表:

[3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]

如何删除重复的元素并表示相同的元素,然后是重复的次数? 示例输出:

[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

其中3重复6次...... 1重复6次......等等

4 个答案:

答案 0 :(得分:6)

您可以在此处使用itertools.groupby生成器函数:

>>> from itertools import groupby                                              
>>> lst = [3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]
>>> def solve(seq):
    for k, g in groupby(seq):
        length = sum(1 for _ in g)
        if length > 1:
            yield k
            yield length
        else:
            yield  k
...             
>>> list(solve(lst))
[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

答案 1 :(得分:0)

itertools是最好的解决方案,但对于没有导入的不同选择,我们可以使用dict:

od = {}

prev = None
out = []
for ele in l:
    if ele != prev and prev in od:
        out.extend((prev, od[prev])) if od[prev] > 1 else out.append(prev)
        od[prev] = 0
    od.setdefault(ele, 0)
    od[ele] += 1
    prev = ele
out.extend((ele, od[ele])) if od[ele] > 1 else out.append(ele)
print(out)
[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

或者在使用效率更高defaultdict的函数中,在dict中存储数据需要更多内存,但使用groupby可能是更快的解决方案:

def grp1(l):
    od = defaultdict(int)
    prev = None
    out = []
    for ele in l:
        if ele != prev and prev in od:
            out.extend((prev, od[prev])) if od[prev] > 1 else out.append(prev)
            od[prev] = 0
        od[ele] += 1
        prev = ele
    out.extend((ele, od[ele])) if od[ele] > 1 else out.append(ele)
    return out
[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

有趣的是,它的速度更快,可能是因为我们不必遍历每个子列表来获取len:

In [33]: l = [choice(l) for _ in range(100000)]

In [34]: timeit grp1(l)
10 loops, best of 3: 23.9 ms per loop

In [35]: timeit list(solve(l))
10 loops, best of 3: 33.9 ms per loop

In [36]: list(solve(l)) == grp1(l)
Out[36]: True

答案 2 :(得分:-1)

不使用itertools的替代解决方案是:

my_list = [3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]
new_list = []

new_list.append(my_list[0]) #adding first element

count = 1 #variable for counting repeated elements
i = 1 #iterator through list

l = len(my_list)

while i < l:
    while i < l and my_list[i] == my_list[i-1]:
        count +=1
        i+=1
    if count > 1:
        new_list.append(count)
        count = 1 #returning to original default value
    else:
        new_list.append(my_list[i])
        i+=1

print(new_list)

答案 3 :(得分:-1)

作为替代答案,您可以使用递归函数和iter来使用索引:

def refiner(li,new=[]):
     it=iter(li[1:])
     for i,j in enumerate(li[:-1],1):
            curr=next(it)
            if j!=curr :
                if i>1:
                  new+=[j,i]
                  return refiner(li[i:],new)

                elif i==len(li)-1:                  
                  new+=[j,curr]
                  return new

                else:
                    new+=[j]
                    return refiner(li[i:],new)

            elif i==len(li)-1:
                  new+=[j,i+1]
                  return new

     return new

样本:

l=[3, 3, 3, 3, 3, 3, 100, 1, 1, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 1, 1]
print refiner(l)
[3, 6, 100, 1, 6, 200, 3, 3, 100, 1, 3]

l=[7, 7, 3, 9, 3, 3, 100, 1, 5, 1, 1, 1, 1, 200, 3, 3, 3, 100, 1, 7, 1]
print refiner(l)
[7, 2, 3, 9, 3, 2, 100, 1, 5, 1, 4, 200, 3, 3, 100, 1, 7, 1]