Python - 找到 2 个列表的补充

mic*_*-ko 1 python compare numpy list complement

我正在寻找一种方法,可以让我在比较 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]
Run Code Online (Sandbox Code Playgroud)

目前输出如下所示: [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]

我究竟做错了什么?

Nat*_*iel 10

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

list(set(numbers) - set(A))
Run Code Online (Sandbox Code Playgroud)
[1, 3, 4, 7, 8]
Run Code Online (Sandbox Code Playgroud)

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

from collections import Counter

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

diff = c1 - c2
print(list(diff.elements()))
Run Code Online (Sandbox Code Playgroud)