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

如何在python中检查两个列表之间的公共元素,python,list,Python,List,当我尝试检查列表中的重叠元素时,我遇到了一些麻烦 这意味着我必须检查两个列表之间的公共元素 我的程序的工作方式是,玩家输入某艘船的两端坐标,然后创建一个所有船只坐标的列表(即如果他们输入(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 List

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

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

我的程序的工作方式是,玩家输入某艘船的两端坐标,然后创建一个所有船只坐标的列表(即如果他们输入
(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中,而不是单独检查它们。

将找到任何公共元素:

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

如果存在重叠,则要再次选择坐标

for i in ListB:
    if i in ListA:
        print("There is an overlap")
        i=(yourcoordinateshere)
否则您要将其添加到
列表a

else:
    print("There is no overlap")
    ListA.append(i)

不确定这是否有帮助

In [1]: from collections import Counter

In [2]: import random

In [3]: lst = [random.randrange(0, 9) for i in xrange(1000)]

In [4]: counted = Counter(lst)

In [7]: counted.most_common(10)
Out[7]: 
[(2, 125),
 (0, 123),
 (5, 120),
 (8, 118),
 (7, 111),
 (1, 107),
 (4, 104),
 (6, 102),
 (3, 90)]
字典 如果在实践中:

 len(ListA) * len(ListB) * ExpectedNumberOfCollisionChecks
是重要的,那么对较长的列表使用字典可能是有意义的,因为字典查找的时间复杂度为:

  • 平均值:O(1)
  • 最坏情况:O(n)
其中平均值为预期值,最坏情况仅在选择了错误的哈希函数时发生

相交集 公认的答案建议使用
set.intersection
。答案是:

  • 平均值:O(n)
  • 最坏情况:O(n^2)
修改代码 对原始代码的唯一更改是将
ListA
转换为
MapA

MapA = {(1,1): True, (1,2): True, (1,3): True,(1,4): True, (1,5): True}
ListB = [(1,1),(2,1),(3,1)]

for i in ListB:
    if MapA.get(i):
        print("There is an overlap")
        #choose coordinates again
    else:
        print("There is no overlap")
        #add to ListA and next ship's coordinate chosen
评论 更进一步说,每次用户输入新坐标(即
ListB
更改)时,必须运行整个交叉点操作。另一方面,最昂贵的操作:哈希
ListA
,只发生一次。从字典中插入和删除具有良好的时间复杂性:

  • 平均值:O(1)
  • 最坏情况:O(n)

对于列表,如果顺序无关紧要,那么插入列表总是O(1),而不管我们是否关心顺序,删除总是O(n)。

这里可能有10个相同的问题。在网上还有10个。使用谷歌叔叔。可能重复感谢,太好了,现在都排序好了