Python在两个列表中匹配元素

Python在两个列表中匹配元素,python,Python,考虑以下示例: list1 = [[A,B,C,D],[A,B,C,D],[A,B,C,D]] list2 = [[B,C],[B,C],[B,C]] 我想在列表1中创建一个新的项目列表,该列表与两个列表中的B、C相匹配。例如: list1 = [[1,A,B,2],[1,D,E,3],[2,F,G,4]] list2 = [[A,B],[B,C],[F,G]] 因此,在匹配上述条件后,我希望结果为: newlst = [[1,A,B,2],[2,F,G,4]] 我试图在列表2中使用for

考虑以下示例:

list1 = [[A,B,C,D],[A,B,C,D],[A,B,C,D]]
list2 = [[B,C],[B,C],[B,C]]
我想在列表1中创建一个新的项目列表,该列表与两个列表中的B、C相匹配。例如:

list1 = [[1,A,B,2],[1,D,E,3],[2,F,G,4]]
list2 = [[A,B],[B,C],[F,G]]
因此,在匹配上述条件后,我希望结果为:

newlst = [[1,A,B,2],[2,F,G,4]]
我试图在列表2中使用for循环和where行[1],但这不起作用。我还尝试:

match = set(list1) & set(list2)

这也不起作用。

这看起来像是给了你想要的:

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]]

我不知道你的固定方法要去哪里。因为&是位运算符。但您要做的是循环列表1,并检查第2个和第3个元素是否与列表2中的任何元素匹配。 这可以通过列表理解在一行中完成

newlst = [i for i in list1 if i[1:3] in list2]
这相当于-

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)