1

I have a list like this,

l=[1,1,1,1,2,2,2,3,3,3,3,3,3,4,4,5,6,6,6,5,5,5,7,7,8,8,8,8,8,9,9,9,10,10]

Now I want to select only one values of repeating value continuously, so the output should look like,

l=[1,2,3,4,5,6,5,7,8,9,10]

I could do this using a for loop checking the next values with the previous and append to a list, But the execution time is huge in that case, Looking for shortcuts to do it most efficiently.

yatu
  • 86,083
  • 12
  • 84
  • 139
Kallol
  • 2,089
  • 3
  • 18
  • 33
  • If iterating through the list and collecting repeating values is "huge time" than what kind of O(?) you are looking for? Because iterating is O(n). Maybe you have some additional conditions as a memory limit or something else? I doubt you can do it less than O(n) – Valentin Briukhanov Dec 27 '19 at 14:16
  • Also, see [Remove following duplicates in a numpy array](https://stackoverflow.com/q/37839928/7851470) – Georgy Dec 27 '19 at 15:05

3 Answers3

6

You can use itertools.groupby to group consecutive values and keep only the grouping key:

from itertools import groupby

[k for k,_ in groupby(l)]
# [1, 2, 3, 4, 5, 6, 5, 7, 8, 9, 10]
yatu
  • 86,083
  • 12
  • 84
  • 139
0

Use the set data structure to remove duplicates and convert it back to a list:

l = [1,1,1,1,2,2,2,3,3,3,3,3,3,4,4,5,6,6,6,5,5,5,7,7,8,8,8,8,8,9,9,9,10,10]

# remove duplicates
num = set(l)

# convert the set of unique values back to a list
num = list(num)

print(num)

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Somraj Chowdhury
  • 983
  • 1
  • 6
  • 14
0

You can use itertools.groupby or something like this (I haven't used zip or slices on purpose and tried to keep it as simple as possible)

def group_by(array):
    if not array:
        return array
    prev = array[0]
    result = [prev]
    for el in array:
        if el != prev:
            result.append(el)
        prev = el
    return result

P.S. Yes, with zip or enumerate or islice it can be more elegant, I know :-)

Valentin Briukhanov
  • 1,263
  • 9
  • 13