Python removes equal lists

I have a list of equals in my list a:

a = [[a],[a],[b],[b],[c],[c]]

      

How can I remove equal lists so that I have the following:

a = [[a],[b],[c]]

      

I tried to do it with a set, but it doesn't work:

my_set = set()
for elem in a:
    my_set.add(elem)
for x in my_set:
    print(x)

      

+3


source to share


6 answers


You can try this:



a = [['a'],['a'],['b'],['b'],['c'],['c']]
b = list()
for item in a:
    if item not in b:
        b.append(item)

      

+5


source


numpy

is one of the options



import numpy as np
a = [['a'],['a'],['b'],['b'],['c'],['c']] 
np.unique(a).tolist() #  ['a', 'b', 'c']

      

+3


source


If you don't mind using itertools

:

[x for x,_ in itertools.groupby(sorted(a))]
#[['a'], ['b'], ['c']]

      

If you do, convert the lists to tuples, create a set of them, and then convert back to lists:

list(map(list, set(map(tuple, a))))
#[['b'], ['c'], ['a']]

      

+2


source


A variation on @ DYZ's answer that works on lists containing identical elements regardless of order:

[x for x,_ in itertools.groupby(map(set, a))]

      

For example:

>>> a = [['a'],['a'],['b'],['b'],['c', 'a'],['a', 'c']]
>>> [list(x) for x,_ in itertools.groupby(map(set, a))]
[['a'], ['b'], ['a', 'c']]

      

If ['c', 'a']

both are ['a', 'c']

not considered equal (see comments below from @DYZ), you can do something like this with set()

:

map(list, set(map(tuple, a)))

      

0


source


If ['c', 'a']

and ['a', 'c']

are not considered to be equal, you can do something like this with the help of set()

:

map(list, set(map(tuple, a)))

      

0


source


You can use a list instead.

d = [it for i, it in enumerate(a) if it not in a[0:i]]
print(d)

      

0


source







All Articles