如何在python中检查两个列表之间的公共元素

bri*_*ass 1 python list

当我尝试检查列表中的重叠元素时,我遇到了一些麻烦.

这意味着我将不得不检查两个列表之间的共同元素.

在我的程序的工作方式是,玩家进入一定船舶他们的两个端部坐标,它就会创建一个列表出来的这一切船舶坐标(IE的,如果他们进入(1,1)(1,5),它将创造[(1,1),(1,2),(1,3),(1,4),(1,5)]

我也尝试使用以下代码,但它不适用于我想要的方式:

ListA = [(1,1),(1,2),(1,3),(1,4),(1,5)]
ListB = [(1,1),(2,1),(3,1)]

    for i in ListB:
        if i in ListA:
            print("There is an overlap")
            #choose coordinates again
        else:
            print("There is no overlap")
            #add to ListA and next ship's coordinate chosen
Run Code Online (Sandbox Code Playgroud)

我想让程序通过集体考虑来检查A中的任何元素是否在B中,而不是单独检查它们.

Pad*_*ham 8

set.intersection将找到任何常见元素:

ListA = [(1,1),(1,2),(1,3),(1,4),(1,5)]
ListB = [(1,1),(2,1),(3,1)]
print(set(ListA).intersection(ListB))
set([(1, 1)])
Run Code Online (Sandbox Code Playgroud)

除非顺序很重要,否则将元组存储在集合中也是一样的:

st_a = {(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)}
st_b = {(1, 1), (2, 1), (3, 1)}
print(st.intersection(st_b))
Run Code Online (Sandbox Code Playgroud)

将其添加到您的代码中:

if st_a.intersection(st_b):
     print("There is an overlap")            
else:
    print("There is no overlap")
Run Code Online (Sandbox Code Playgroud)