Removing elements that have consecutive duplicates

社会主义新天地 提交于 2019-11-26 11:50:19
>>> L = [1,1,1,1,1,1,2,3,4,4,5,1,2]
>>> from itertools import groupby
>>> [x[0] for x in groupby(L)]
[1, 2, 3, 4, 5, 1, 2]

If you wish, you can use map instead of the list comprehension

>>> from operator import itemgetter
>>> map(itemgetter(0), groupby(L))
[1, 2, 3, 4, 5, 1, 2]

For the second part

>>> [x for x, y in groupby(L) if len(list(y)) < 2]
[2, 3, 5, 1, 2]

If you don't want to create the temporary list just to take the length, you can use sum over a generator expression

>>> [x for x, y in groupby(L) if sum(1 for i in y) < 2]
[2, 3, 5, 1, 2]

Oneliner in pure Python

[v for i, v in enumerate(your_list) if i == 0 or v != your_list[i-1]]

Here is a solution without dependence on outside packages:

list = [1,1,1,1,1,1,2,3,4,4,5,1,2] 
L = list + [999]  # append a unique dummy element to properly handle -1 index
[l for i, l in enumerate(L) if l != L[i - 1]][:-1] # drop the dummy element

Then I noted that Ulf Aslak's similar solution is cleaner :)

To Eliminate consecutive duplicates of list elements; as an alternative, you may use itertools.izip_longest() with list comprehension as:

>>> from itertools import izip_longest

>>> my_list = [1,1,1,1,1,1,2,3,4,4,5,1,2]
>>> [i for i, j in izip_longest(my_list, my_list[1:]) if i!=j]
[1, 2, 3, 4, 5, 1, 2]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!