简体   繁体   中英

intersection of lists return all within list of lists

List1 = [['A0.01', 'GENERIC NOTES'],['A0.02', 'ANOTHER GENERIC NOTE'],['A0.03', 'YET ANOTHER GENERIC NOTE']]
List2 = ['A0.01','A0.03']

and I want to find the intersection of the two lists and return a list of all items if there is a match. Below is what I have tried:

result = [[j for j in view if j in List2] for view in List1]

This returns me the matching values in List1

[['A0.01'],[],['A0.03']]

but I want the rest of the values within that matching list item as well. Below is what I intend the result to be:

['A0.01', 'GENERIC NOTES'],['A0.03', 'YET ANOTHER GENERIC NOTE']

How can I achieve this. I appreciate any help!

I'm sure there are many ways to do this.

Here is one

>>> matches = set(item[0] for item in List1).intersection(List2)
>>> matches
{'A0.03', 'A0.01'}
>>> [item for item in List1 if item[0] in matches]
[['A0.01', 'GENERIC NOTES'], ['A0.03', 'YET ANOTHER GENERIC NOTE']]

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