尝试检查列表中的重叠元素时遇到麻烦。
这意味着我将必须检查两个列表之间的共同元素。
我的程序的工作方式是,玩家输入特定船只的两个末端坐标,然后从所有船只坐标中创建一个列表(即,如果他们输入(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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句