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

如何在Python中查找向量满足条件的最后K个索引(类Matlab find)

Efficiently Find the Last N Matching Indices in Python (Without Full Array Traversal)

Great question—since you want to avoid scanning the entire array and stop immediately once you've found the last 2 matching indices (just like MATLAB's find(v <5 , 2,'last')), here's a clear, efficient Python implementation using NumPy:

Step-by-Step Implementation

import numpy as np

v = np.arange(10)
target_count = 2
condition = v < 5
matching_indices = []

# Traverse the array from the end backwards
for idx in reversed(range(len(v))):
    if condition[idx]:
        matching_indices.append(idx)
        # Stop as soon as we've collected the required number of indices
        if len(matching_indices) == target_count:
            break

# Reverse to get indices in ascending order (aligning with MATLAB's output logic)
matching_indices = matching_indices[::-1]
print(matching_indices)  # Output: [3, 4]

Why This Works

  • Early Termination: We start checking from the last element and halt the moment we've found 2 matching indices—no need to iterate through the entire array.
  • Clear Logic: The flow is easy to follow: reverse iterate, collect matches until we hit our target count, then reorder to get the ascending index sequence (matching the intuitive order you'd expect, with Python's 0-based [3,4] corresponding to MATLAB's 1-based result).
  • Efficiency: For large arrays, this saves meaningful computation time compared to methods like np.where (which scans the entire array first to collect all matches, then slices the last N elements—something you explicitly want to avoid).

内容的提问来源于stack exchange,提问作者Alexander Chervov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:32:13