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

如何在Python/Numpy中从第二行开始按1,2,0顺序遍历数组

实现方法

普通Python列表场景

如果你的a是普通嵌套列表,直接通过指定索引顺序遍历即可:

a = [[1, -1], [0, 1], [-1.5, -1]]
# 定义目标索引顺序
index_order = [1, 2, 0]
for idx in index_order:
    row = a[idx]
    # 这里替换为你需要的行处理逻辑
    print(row)

Numpy数组场景

如果a是Numpy数组,有两种实用方式:

方式1:遍历索引列表取行

import numpy as np

a = np.array([[1, -1], [0, 1], [-1.5, -1]])
index_order = [1, 2, 0]
for idx in index_order:
    row = a[idx]
    # 这里替换为你需要的行处理逻辑
    print(row)

方式2:花式索引重组数组后遍历

利用Numpy的花式索引直接生成按指定顺序排列的新数组,再遍历行:

import numpy as np

a = np.array([[1, -1], [0, 1], [-1.5, -1]])
reordered_a = a[[1, 2, 0]]
for row in reordered_a:
    # 这里替换为你需要的行处理逻辑
    print(row)

若需要多次使用该顺序的数组,方式2会更高效。

内容的提问来源于stack exchange,提问作者Rematlen Bollobani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 00:09:24