从列表中删除重复项但只保留一些

时间:2017-10-14 07:58:48

标签: python algorithm python-2.7

给定数组

[1,2,2,3,2,2,4,5,5,6,7] 

作为输入。如何过滤列表以便输出

[1,2,3,2,4,5,6,7] 

请注意

[2,2] -> [2]

,也是

[1,2,2,1] -> [1,2,1]
[1,2,3,3,2,1] -> [1,2,3,2,1]

3 个答案:

答案 0 :(得分:3)

使用itertools.groupby()

In [1]: lst = [1,2,2,3,2,2,4,5,5,6,7]

In [2]: from itertools import groupby

In [3]: [next(g) for _,g in groupby(lst)]
Out[3]: [1, 2, 3, 2, 4, 5, 6, 7]

答案 1 :(得分:1)

这是两个指针问题。这是伪代码:

start = 0
end = 1
while(end < len(arr)):
    if(arr[end] != arr[start]):
        arr[start + 1] = arr[end]
        start += 1
    end += 1
# end of while loop

# now arr[0... start] holds the result

具有恒定空间的时间复杂度O(n)

答案 2 :(得分:0)

使用zip的另一种方法:

>>> a = [1, 2, 2, 3, 2, 2, 4, 5, 5, 6, 7]
>>> [i for i,j in zip(a, a[1:] + [not a[-1]]) if i != j]
[1, 2, 3, 2, 4, 5, 6, 7]