Reputation: 2366
I have a list of lists and some of the lists have a list in it:
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
I have tried getting uniqueness to obtain:
x = [[[1,2],3],[[3,4],5]]
But no luck - any ideas?
I have so far used:
unique_data = [list(el) for el in set(tuple(el) for el in x)]
on a list of lists which works, but when adding in an element of a list within the list it fails
Upvotes: 2
Views: 90
Reputation: 239443
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
print [item for idx, item in enumerate(x) if x.index(item) == idx]
# [[[1, 2], 3], [[3, 4], 5]]
We can do this in O(N) like this
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
x = tuple(tuple(tuple(j) if isinstance(j, list) else j for j in i) for i in x)
from collections import OrderedDict
print [[list(j) if isinstance(j, tuple) else j for j in i] for i in OrderedDict.fromkeys(x).keys()]
# [[[1, 2], 3], [[3, 4], 5]]
Upvotes: 7
Reputation: 1319
This will do what you want.
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
p = {hash(str(item)): item for item in x}
uniques = [ val for val in p.values()]
Upvotes: 3
Reputation: 179
x = [[[1,2],3],[[3,4],5], [[1,2],3]]
z = []
for i in x:
if i not in z:
z.append(i)
print z
[[[1, 2], 3], [[3, 4], 5]]
Is this what u r looking for??
Upvotes: 0