Find the intersection of two lists

Asked 2 years ago, Updated 2 years ago, 80 views

If the list is a one-dimensional array, this is how you get it.

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = [val for val in b1 if val in b2]

#or

def intersect(a, b):
    return list(set(a) & set(b))
print intersect(b1, b2)

By the way, how do you find the intersection of these overlapping lists?

c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

The intersection result I want is [[13,32],[7,13,28],[1,6]].

python list intersection

2022-09-21 21:14

1 Answers

Python built-in function at intersection of one-dimensional lists You can also write set.intersection(). However, this function can be written in the set type, so when obtaining the intersection of the list, you must convert the list to set, set.intersection, and then convert the result back to list.

b1 = [1,2,3,4,5,9,11,15]
b2 = [4,5,6,7,8]
b3 = list(set(b1).intersection(b2))

And for nested lists, you can do two things:

c3 = [filter(lambda x: x in c1, sublist) for sublist in c2]

To explain the code, (...) for list in c2 tours items (lists with elements) on the external list, respectively filter() traverses an item (integer) in this internal list to make sure it is in c1.

If you are not familiar with Lambda, please use the following method

c3 = [ list(set(c1).intersection(i)) for i in c2]


2022-09-21 21:14

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.