Python - 找到 2 个列表的补充

标签 python list numpy compare complement

<分区>

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

Complement of Two Lists?

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]

我做错了什么?

最佳答案

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

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

关于Python - 找到 2 个列表的补充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55265999/

相关文章:

python - QWebView : is it possible to highlight terms and do keyboard navigation?

python - 将使用 pygame 的 python 程序编译为可执行文件

python - 如何移动 matplotlib 图中的一条线?

r - 将向量与向量列表匹配

python - 如何通过在最后一个元素处拆分数组来将一维数组拆分为 NumPy 中的二维数组?

Python Sphinx autodoc 和装饰成员

python - 如何显示输入的数字在哪个位置?

Python - 二维列表 - 在一列中查找重复项并在另一列中求和值

python - 在 Numpy 中将一维数组添加到三维数组

python - 形状(150,) 和形状(150,1) 有什么区别?