You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何高效比较数组中双元素与双元素列表生成布尔数组?

Efficiently Check if Subarrays Match a Target in NumPy

Hey there! I get exactly what you're trying to do—you want a 1D boolean array where each entry tells you if the corresponding subarray in a matches [0, 1] exactly, instead of the element-wise 2D boolean array you’re getting now. The loop-based approach you’re using works, but it’s definitely not the most efficient for large datasets. Let’s fix that with vectorized NumPy operations, which are way faster and more memory-friendly.

The Problem with Your Current Approach

When you run a == [0, 1], NumPy uses broadcasting to compare each element of a to the corresponding element in the target [0,1]. That’s why you get a 2D array—each subarray gives two boolean values instead of one combined result.

The Efficient Solution: Use np.all() with Axis Parameter

The simplest way to get your desired result is to use np.all() to check if all elements in each subarray match the target. Specify axis=1 to tell NumPy to perform this check along each row (each subarray):

import numpy as np

a = np.array(([0, 0], [0, 1], [1, 0], [1, 1]))
c = np.all(a == [0, 1], axis=1)

print(c)
# Output: array([False,  True, False, False])

How This Works

  • a == [0,1] still generates the 2D element-wise boolean array you saw before.
  • np.all(..., axis=1) collapses each row into a single boolean value: True only if both elements in the row match the target, otherwise False.

Alternative: Using np.equal() Explicitly

If you prefer more explicit syntax, you can use np.equal() instead of the == operator—it does the same thing, just written differently:

c = np.all(np.equal(a, [0, 1]), axis=1)

Why This Is Better Than Looping

NumPy's vectorized operations are implemented in C, so they avoid the overhead of Python-level loops. For large arrays, this will be orders of magnitude faster than raveling and looping through elements manually.

内容的提问来源于stack exchange,提问作者tong jiang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:25:23