如何高效比较数组中双元素与双元素列表生成布尔数组?
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:Trueonly if both elements in the row match the target, otherwiseFalse.
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

