Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have a list named CB whose elements are also lists, how to keep only the unique elements of CB? np.unique() or list(set()) do not work

I have a very long list named CB with possibly repeated elements. For example, CB could be [[0, 0], [0, 1], [0, 2], [0, 1], [1, 1], [1, 2], [0, 2], [1, 2], [2, 2]]. Each element in CB is a list of sorted numbers.

In this example, I want to keep
[[0,0], [0,1], [0,2], [1,1], [1,2], [2,2]].

I’ve tried to use CB1=np.unique(CB), but it returns [0,1,2], which is not what I wanted.
I also tried to use CB1=list(set(CB)), but got the following error: TypeError: unhashable type: ‘list’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How to solve this problem? It would be great if you could solve it with the simplest possible code. A python function or one line of code would be awesome. Thanks!

>Solution :

If you use np.unique, you want to use the axis keyword argument:

data = [[0, 0], [0, 1], [0, 2], [0, 1], [1, 1], [1, 2], [0, 2], [1, 2], [2, 2]]
np.unique(data, axis=0)

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

if you want to use set, you need to convert to hashable type, e.g. tuple:

data = map(tuple, data)
set(data)

{(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)}

if you need then converted back to the original list type, then the complete 1-liner would be:

data = list(map(list,set(map(tuple, data))))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading