-1

The post is similar to this but what I want, is to remove specific consecutive duplicate in a list. So let's say we have this list:

[1,1,1,2,2,3,2,4,4,4,1]

I want to have:

[1,2,2,3,2,4,4,4,1]

I want to remove only the "ones". I am trying itertools.groupby but I haven't found a way to do it.

Georgy
  • 12,464
  • 7
  • 65
  • 73
  • 3
    What’s the logic? Do you want to remove all duplicate ones? All duplicate ones at the beginning of the string? All duplicates at the beginning of the string regardless of value? – Mark Apr 15 '20 at 07:15
  • Ultimately it's very similar to the solution in the duplicate; use `groupby`, which returns tuples likes `(1, (1, 1, 1))`, you just need to decide whether you'll use the first item or the second item depending on whether it's `1` or not… – deceze Apr 15 '20 at 07:23
  • The pattern is: Whereever there is duplicate "1" should be removed. Another example: from [1,1,1,2,2,3,2,1,1,4,4,4,1,1,1,1] to [1,2,2,3,2,1,4,4,4,1] – Angelos Papangelis Apr 15 '20 at 08:21

2 Answers2

4

You could use itertools.groupby and use the grouping key to either keep the key or keep the returned group:

l = [1,1,1,2,2,3,2,4,4,4,1]

from itertools import chain, groupby

list(chain.from_iterable([k] if k==1 else v for k,v in groupby(l)))
# [1, 2, 2, 3, 2, 4, 4, 4, 1]
yatu
  • 86,083
  • 12
  • 84
  • 139
  • Nice one , one more similar approach `sum([[1] if i==1 else list(j) for i,j in groupby(a)],[])` – Naga kiran Apr 15 '20 at 07:26
  • 2
    Note that flattening with sum is not really recommended though @Nagakiran , it has higher complexity than necessary – yatu Apr 15 '20 at 07:27
0

If you search for ones at the beginning of the list, you do not need to import a module to do this, it is also possible to iterate over the elements in a for-loop:

your_list = [1,1,1,2,2,3,2,4,4,4,1]
for index, element in enumerate(your_list):
    if element != 1:
        break
if index:
    result = your_list[index-1:]
else:
    result = your_list

This would check for ones, until it finds another number. The index of the other number -1 is meant to be the beginning of the list.

If there is no 1 in the list, index will be zero and the original list is returned.

Jakob Schödl
  • 380
  • 2
  • 16
  • Note that this assumes the searched-for value is at the beginning of the list, and it assumes only the first occurence should be de-duplicated (this requirement is unclear)… – deceze Apr 15 '20 at 07:26
  • Oh, thanks, I assumed that and will edit my answer – Jakob Schödl Apr 15 '20 at 07:27