Skip to main content
 首页 » 编程设计

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

2025年05月04日11freeliver54

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

这意味着我必须检查两个列表之间的共同元素。

我的程序的工作方式是玩家输入某艘船的两端坐标,然后根据所有船坐标创建一个列表(即如果他们输入 (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 

我希望程序通过整体考虑它们来检查 A 中的任何元素是否在 B 中,而不是单独检查它们。

请您参考如下方法:

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

除非顺序很重要,否则最好将元组存储在集合中:

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

将其添加到您的代码中:

if st_a.intersection(st_b): 
     print("There is an overlap")             
else: 
    print("There is no overlap")