简体   繁体   English

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

[英]How to check for common elements between two lists in python

I am having a bit of trouble when I try and check for overlapping elements in list. 我在尝试检查列表中的重叠元素时遇到了麻烦。

This means that I will have to check for common elements between two lists. 这意味着我将不得不检查两个列表之间的共同元素。

The way in which my programme works is that the player enters their two end coordinates for a certain ship, it then creates a list out of this of all of the ships coordinates (ie if they enter (1,1) and (1,5) , it would create [(1,1),(1,2),(1,3),(1,4),(1,5)] 我的程序的工作方式是,玩家输入特定船的两个末端坐标,然后从所有船坐标中创建一个列表(即,如果他们输入(1,1)(1,5) ,它将创建[(1,1),(1,2),(1,3),(1,4),(1,5)]

I have also tried using the following code but it doesn't work for the way I want it to: 我也尝试过使用以下代码,但不适用于我想要的方式:

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

I would like for the program to check to see if any of the elements in A are in B by considering them collectively, instead of checking them individually. 我希望程序通过集体考虑而不是单独检查来检查A中的任何元素是否在B中。

set.intersection will find any common elements: 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)])

Unless order matters it may be just as well to store the tuples in sets: 除非顺序很重要,否则将元组存储在集中也可能是一样的:

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

add it to your code with: 使用以下命令将其添加到您的代码中:

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

If there is an overlap you want to choose coordinates again; 如果有重叠,则要再次选择坐标;

for i in ListB:
    if i in ListA:
        print("There is an overlap")
        i=(yourcoordinateshere)

Else you want to add it to ListA ; 否则,您要将其添加到ListA

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

Not sure if this helps... 不确定是否有帮助...

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

Dictionary 字典

If in practice: 如果在实践中:

 len(ListA) * len(ListB) * ExpectedNumberOfCollisionChecks

is significant then it may make sense to use a dictionary for the longer list because the time complexity for a dictionary lookup is: 是重要的,那么对于较长的列表使用字典可能是有意义的,因为字典查找的时间复杂度为:

  • Average: O(1) 平均值:O(1)
  • Worst case: O(n) 最坏的情况:O(n)

Where the average is expected and the worst case happens only when a bad hash function has been selected. 仅当选择了错误的哈希函数时,才可以预期平均值,而最坏的情况才会发生。

Intersecting Sets 相交集

The accepted answer proposes using set.intersection . 接受的答案建议使用set.intersection The time complexity of set.intersection is: set.intersection时间复杂度是:

  • Average: O(n) 平均值:O(n)
  • Worst case: O(n^2) 最坏的情况:O(n ^ 2)

Modified Code 修改后的代码

The only change to your original code is conversion of ListA to MapA . 你原来代码中的唯一变化是转换ListAMapA

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

Comments 评论

Going further, the entire intersection operation has to be run each time the user inputs new coordinates (ie ListB changes). 更进一步,每次用户输入新坐标(即ListB更改)时,都必须运行整个相交操作。 On the other hand the expensive operation most expensive operation: hashing ListA , only occurs once. 另一方面,最昂贵的操作最昂贵的操作:哈希ListA ,只发生一次。 Insertions and deletions from a dictionary have good time complexity: 字典中的插入和删除具有很高的时间复杂度:

  • Average: O(1) 平均值:O(1)
  • Worst case: O(n) 最坏的情况:O(n)

For lists, if order does not matter then inserting into a list is always O(1) and regardless of if we care about order deletions are always O(n). 对于列表,如果顺序无关紧要,则插入列表始终为O(1),无论我们是否关心顺序删除,始终为O(n)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM