如何用Python复现MATLAB中基于逻辑数组提取数组元素的代码?
tTacho = tDiff(xDiff == 2) to Python The MATLAB code you're looking to replicate does two core things: first, it creates a boolean mask marking where elements in xDiff equal 2, then uses that mask to pull the corresponding elements from tDiff into tTacho. Here's how to do this in Python, tailored to whether you're using numpy arrays (the closest match to MATLAB's array workflow) or standard Python lists:
Using Numpy Arrays (Recommended for MATLAB-like Behavior)
If you’re working with numpy arrays (the standard for numerical operations in Python), the code is nearly identical to MATLAB:
import numpy as np # Assume xDiff and tDiff are numpy arrays (e.g., created with np.array()) tTacho = tDiff[xDiff == 2]
This works because numpy supports boolean indexing just like MATLAB. The expression xDiff == 2 generates a boolean array matching the shape of xDiff, where each entry is True if the corresponding xDiff element is 2, and False otherwise. Using this mask to index into tDiff extracts only the elements where the mask is True.
Using Standard Python Lists
If you’re working with regular Python lists instead of numpy arrays, a list comprehension will get the job done:
# Assume xDiff and tDiff are standard Python lists tTacho = [t_val for x_val, t_val in zip(xDiff, tDiff) if x_val == 2]
Breakdown of this code:
zip(xDiff, tDiff)pairs up elements from both lists (e.g.,(xDiff[0], tDiff[0]),(xDiff[1], tDiff[1]))- The comprehension iterates over each pair, checks if
x_valequals 2, and adds the correspondingt_valtotTachoif the condition is met.
内容的提问来源于stack exchange,提问作者Steven Goddard

