简体   繁体   中英

Python match elements in two lists of lists

Consider the following example:

list1 = [[A,B,C,D],[A,B,C,D],[A,B,C,D]]
list2 = [[B,C],[B,C],[B,C]]

I want to create a new list of items in list 1 that match B,C from both lists. For example:

list1 = [[1,A,B,2],[1,D,E,3],[2,F,G,4]]
list2 = [[A,B],[B,C],[F,G]]

So after matching the above I want the result to be:

newlst = [[1,A,B,2],[2,F,G,4]]

I attempted to use a for loop and where row[1] in list2 but that didnt work. I also tried:

match = set(list1) & set(list2)

That did not work either.

This looks like it gives what you want:

list1 = [[1, 'A', 'B' ,2], [1, 'D', 'E',3], [2, 'F', 'G', 4]]
list2 = [['A', 'B'], ['B', 'C'], ['F', 'G']]

list3 = [e for (e, k) in zip(list1, list2) if (e[1] == k[0] and e[2] == k[1])]
list3
[[1, 'A', 'B', 2], [2, 'F', 'G', 4]]

I have no idea where you were going with your set approach. Since & is a bitwise operator. But what you want to do is loop over list 1 and check if the 2nd and 3rd element matches any in list 2. This can be done in one line via list comprehension.

newlst = [i for i in list1 if i[1:3] in list2]

This is equivalent to-

newlst = []
#loop over list1
for i in list1:
    #i[1:3] returns a list of 2nd and 3rd element
    #if the 2nd and 3rd element are in the second list
    if i[1:3] in list2:
        newlst.append(i)

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