gpt4 book ai didi

python - 如何在具有有限元值的二维数组中查找缺失的组合/序列

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:03 26 4
gpt4 key购买 nike

对于集合 np.array([1, 2, 3]),其组成元素只有 9 种可能的组合/序列:[1, 1] , [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3].

如果我们有以下数组:

np.array([1, 1],
[1, 2],
[1, 3],
[2, 2],
[2, 3],
[3, 1],
[3, 2])

使用 NumPy/SciPy 确定 [2, 1][3, 3] 丢失的最佳方法是什么?换句话说,我们如何找到序列的逆列表(当我们知道所有可能的元素值时)?使用几个 for 循环手动执行此操作很容易弄清楚,但这会抵消我们通过使用 NumPy 而不是原生 Python 获得的任何速度提升(尤其是对于较大的数据集)。

最佳答案

您可以使用 itertools.product 生成所有可能对的列表并收集所有不在你的数组中的:

from itertools import product

pairs = [ [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 1], [3, 2] ]
allPairs = list(map(list, product([1, 2, 3], repeat=2)))
missingPairs = [ pair for pair in allPairs if pair not in pairs ]
print(missingPairs)

结果:

[[2, 1], [3, 3]]

请注意 map(list, ...)需要将您的列表列表转换为可以与 product 返回的元组列表进行比较的元组列表.如果您的输入数组已经是元组列表,这可以简化。

关于python - 如何在具有有限元值的二维数组中查找缺失的组合/序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48853311/

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