考虑两个排序的 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/