Erel Segal-Halevi
Erel Segal-Halevi

Reputation: 36715

A set of unique lists

I have a lists of lists, e.g.:

[['4bb', '3bb', '3', '1', '2', '4b', '4'],
 ['4bb', '3bb', '1', '3', '2', '4b', '4'],
 ['4bb', '3bb', '1', '2', '3', '4b', '4'],
 ['4bb', '1', '3bb', '3', '2', '4b', '4'],
 ['4bb', '1', '3bb', '2', '3', '4b', '4']]

I want to create a list of shorter lists - only the three rightmost elements of each list, such that the elements are unique, e.g:

[['2', '4b', '4'],
 ['3', '4b', '4']]

I tried to use "set" but this doesn't work because a list is not hashable.

Upvotes: 1

Views: 62

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90889

If the order of sublists in the new list does not matter, You can use a tuple instead of list to store in the set() . tuples are hashable and hence can be added to a set.

Example using set comprehension (for Python 2.7+) -

setlst = {tuple(x[-3:]) for x in lst}
newlst = list(map(list, setlst))

You can use list comprehension with set() as set([<list comp>]) for versions of Python where set comprehension is not supported.

Demo -

>>> lst = [['4bb', '3bb', '3', '1', '2', '4b', '4'],
...  ['4bb', '3bb', '1', '3', '2', '4b', '4'],
...  ['4bb', '3bb', '1', '2', '3', '4b', '4'],
...  ['4bb', '1', '3bb', '3', '2', '4b', '4'],
...  ['4bb', '1', '3bb', '2', '3', '4b', '4']]
>>>
>>> setlst = {tuple(x[-3:]) for x in lst}
>>> newlst = list(map(list, setlst))
>>> newlst
[['2', '4b', '4'], ['3', '4b', '4']]

Upvotes: 3

Maroun
Maroun

Reputation: 95948

You can do the following:

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

The most inner map maps the lists to tuple, and since it's hashable, you can apply set in it. Then you simply map it back to list.

Upvotes: 1

Related Questions