简体   繁体   中英

How to get common elements of two lists, which are themselves lists in python

I have two lists of lists:

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]

and I want to get their intersection, ie, [[3,1],[1,4],[1,'a']] . How can I do this?

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]
intersection = []
for x in l1:
    if x in l2:
        intersection.append(x)
print (intersection)

Use for loop find same elements and append them into another list.

Output;

[[3, 1], [1, 'a'], [1, 4]]
>>> 

Or shorter way , use list comprehensions;

l1 = [[3,1],[1,2],[1,'a'],[1,4]]
l2 = [[3,1],[1,4],[1,5],[1,'a']]

print ([x for x in l1 if x in l2])

Assuming the inner elements will always be in the same order.

out = set(map(tuple, l1)).intersection(map(tuple, l2))

Output

set([(1, 'a'), (3, 1), (1, 4)])

Note that the above returns a set of tuples, not lists. But you can easily convert them back to lists if needed:

map(list, out)

Considering your clarification comments on the question, do it like this:

Convert one of the lists to a set (for the O(1) lookup time), then employ a list comprehension.

>>> l2_s = set(map(tuple, l2))
>>> [x for x in l1 if tuple(x) in l2_s]
[[3, 1], [1, 'a'], [1, 4]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM