gpt4 book ai didi

python - 从两个 numpy 数组中删除匹配的元素

转载 作者:行者123 更新时间:2023-11-28 22:08:32 27 4
gpt4 key购买 nike

考虑两个排序的 numpy 数组:

import numpy as np

a = np.array([1,2,4,4,6,8,10,10,21])
b = np.array([3,3,4,6,10,18,22])

我如何:1.找到出现在两个列表中的元素,并且2. 从每个列表中仅删除该事件的一个 实例。

输出应该是:

a = [1,2,4,8,10,21]

b = [3,3,18,22]

所以即使有重复的,也只会移除一个实例。但是,如果列表是

c = np.array([1,2,4,4,6,8,10,10,10,21])
d = np.array([3,3,4,6,10,10,18,22])

我希望获得新的输出:

c = [1,2,4,8,10,21]

d = [3,3,18,22]

同上。区别在于列表中 10 的数量。列表 d 中的两个 10 中的每一个都从 c 中各取一个 10,留下相同的结果。

post是与我的问题最接近的匹配项,但它从两个列表中删除了所有 重复实例。

最佳答案

您可以使用 collections.Counter :

from collections import Counter

import numpy as np

a = np.array([1, 2, 4, 4, 6, 8, 10, 10, 21])
b = np.array([3, 3, 4, 6, 10, 18, 22])

ca = Counter(a)
cb = Counter(b)

result_a = sorted((ca - cb).elements())
result_b = sorted((cb - ca).elements())

print(result_a)
print(result_b)

输出

[1, 2, 4, 8, 10, 21]
[3, 3, 18, 22]

它返回相同的结果(如预期的那样):

a = np.array([1, 2, 4, 4, 6, 8, 10, 10, 10, 21])
b = np.array([3, 3, 4, 6, 10, 10, 18, 22])

关于python - 从两个 numpy 数组中删除匹配的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58383274/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com