如何在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
相关产品推荐
相关产品推荐

