-1

How to make from this:

[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1]]

to this?

array([[1, 0, 0],
       [1, 0, 1]])

I tried this but it only works with 2 repeated elements. I want it to work for any number of repeated elements.

finalRes = []

for i in range(len(resList)-1):
    if resList[i] == resList[i+1]:
        finalRes.append(resList[i])

finalRes --> [[1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1]]
aaaaaaaa
  • 1
  • 3

2 Answers2

1

Use itertools.groupby:

from itertools import groupby

lst = [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1]]

result = [key for key, _ in groupby(lst)]
print(result)

Output

[[1, 0, 0], [1, 0, 1]]
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
1

You can use numpy.unique to find the unique elements in the array.

Use:

import numpy as np

arr = [[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 1], [1, 0, 1], [1, 0, 1]]
unique_arr = np.unique(arr, axis=0)
print(unique_arr)

This prints:

[[1 0 0]
 [1 0 1]]
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53