首页 > 解决方案 > Python如何计算两个数组中特定值的交集?

问题描述

我有两个数组 A、B,它们的值都是 [0 , 1 , 2] (大小相同)我想计算值 1 的索引的交集。换句话说,我想检查值 1 基数的精度在数组 A 上。

到目前为止,我已经尝试过地图功能,但它不起作用。

temp = list(map(lambda x,y: (x is y) == 1 ,A ,B))

然而结果并不是我所期望的。您能否就如何解决此问题提出一些建议或示例?

标签: pythontensorflow

解决方案


尝试这个:

x = np.array([0, 1, 2, 3, 1, 4, 5])
y = np.array([0, 1, 2, 4, 1, 3, 5])
print(np.sum(list(map(lambda x,y: (x==y==1) , x, y))))

输出:

2

张量流代码:

elems = (np.array([0, 1, 2, 3, 1, 4, 5, 0, 1, 2, 3, 1, 4, 5]), np.array([0, 1, 2, 4, 1, 3, 5, 0, 1, 2, 3, 1, 4, 5]))
alternate = tf.map_fn(lambda x: tf.math.logical_and(tf.equal(x[0], 1), tf.equal(x[0], x[1])), elems, dtype=tf.bool)
print(alternate)
print(tf.reduce_sum(tf.cast(alternate, tf.float32)))

输出:

tf.Tensor([False True False False True False False False True False False True False False], shape=(14,), dtype=bool)
tf.Tensor(4.0, shape=(), dtype=float32)

推荐阅读