1

我正在寻找一种方法,可以让我在比较 2 个列表时检查缺少哪些元素。很像这个线程,但我想用 NumPy Python 写这个。

两个列表的补充?

import numpy as np

numbers = np.array([1,2,3,4,5,6,7,8,9])
A = np.array([2,5,6,9])

def listComplementElements(list1, list2):

    storeResults = []

    for i in list1:
        for j in list2:

            if i != j:
                #write to storeResults if 2 numbers are different
                storeResults.append(i)
            else:
                #if numebrs are equal break out of the loop
                break

    return storeResults            

result = listComplementElements(numbers, A)
print(result) #expected result [1,3,4,7,8]

目前输出如下所示: [1, 1, 1, 1, 3, 3, 3, 3, 4, 4, 4, 4, 5, 6, 6, 7, 7, 7, 7, 8, 8、8、8、9、9、9]

我究竟做错了什么?

4

2 回答 2

11

这将为您提供两个数组的补码:

list(set(numbers) - set(A))
[1, 3, 4, 7, 8]

如果您有要保留的重复值,可以使用以下内容:

from collections import Counter

c1 = Counter(numbers)
c2 = Counter(A)

diff = c1 - c2
print(list(diff.elements()))
于 2019-03-20T16:46:18.697 回答
1

这就是你想要的:

import numpy as np

numbers = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
A = np.array([2, 5, 6, 9])

def listComplementElements(list1, list2):
    storeResults = []

    for num in list1:
        if num not in list2: # this will essentially iterate your list behind the scenes
            storeResults.append(num)

    return storeResults

result = listComplementElements(numbers, A)
print(result) #expected result [1,3,4,7,8]

印刷:

[1、3、4、7、8]

您应该只有一个循环,然后说if not in要评估与第二个列表的关系。否则你会不必要地循环,就像你看到的那样,它会多次输出结果!此外,使用类似is inor的运算符not in使您的代码比尝试理解许多嵌套循环更具可读性:)

于 2019-03-20T16:53:01.780 回答