python - Python如何计算两个数组中特定值的交集?
问题描述
我有两个数组 A、B,它们的值都是 [0 , 1 , 2] (大小相同)我想计算值 1 的索引的交集。换句话说,我想检查值 1 基数的精度在数组 A 上。
到目前为止,我已经尝试过地图功能,但它不起作用。
temp = list(map(lambda x,y: (x is y) == 1 ,A ,B))
然而结果并不是我所期望的。您能否就如何解决此问题提出一些建议或示例?
解决方案
尝试这个:
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)
推荐阅读
- protocol-buffers - protobuf : 定义一个 parentS <-> childrenS 关系
- hyperledger-fabric - Hyperledger Fabric - 链码调用版本(用于客户端版本变体)
- javascript - 检查 if 语句以附加值的正确方法是什么?
- google-bigquery - xxxx@gmail.com 在项目 yyyy 中没有 bigquery.jobs.create 权限
- python - tensorflow 占位符 - 理解 `shape=[None,`
- amazon-web-services - AWS AppSync、Cognito 和 S3
- javascript - 在移动网络中保持滚动
- angular-material - 将复选框设置为不确定
- javascript - 模糊图像画布
- javascript - 从 vanilla 脚本中捕获 Vue 中的事件