These are my two lists;
k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,9]]
kDash = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,6], [1,2]]
My output should be the following;
[[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
how can I get to this output?
thank you in advance
You will have to convert the lists to list of tuples, and then use the intersection. Note that below solution may have elements in a different order, and duplicates will obviously not be there, since I'm using set.
In [1]: l1 = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,9]]
In [2]: l2 = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4], [5,6], [1,2]]
In [3]: [list(x) for x in set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))]
Out[3]: [[1, 2], [5, 6, 2], [3], [4]]
You can alternatively save the intersection in a variable and get the final list, if order, duplicates are necessary:
In [4]: intersection = set(tuple(x) for x in l1).intersection(set(tuple(x) for x in l2))
In [5]: [x for x in l1 if tuple(x) in intersection]
Out[5]: [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]
And the intersection, just in case if you are interested.
In [6]: print intersection
set([(1, 2), (5, 6, 2), (3,), (4,)])
This will work pretty well for large lists, but if the lists are small, do explore the other solution by @timegb (whose solution will be highly unoptimal for longer lists)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With