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

Python循环带步长的索引处理及NumPy数组优雅赋值方案

问题:按指定步长遍历NumPy数组并处理元素写入结果数组

需要在嵌套循环中按指定步长遍历NumPy数组,将处理后的元素写入结果数组对应位置。目前手动维护索引的代码可实现功能,但想找更优雅的实现方式。原代码及输出如下:

import numpy as np

basearray = np.array([[10, 20, 30, 40, 50],
             [15, 16, 17, 18, 19],
             [25, 26, 27, 28, 29],
             [35, 36, 37, 38, 39]])

stepx=0
stepy=0
incrementx=2
incrementy=2
resultarray=np.zeros(((len(basearray)),len(basearray[1])))

for x in basearray[::incrementx]:
    stepy=0
    for y in x[::incrementy]:
        resultarray[stepx][stepy]=y*2
        stepy=stepy+incrementy
    stepx=stepx+incrementx
print(resultarray)

原输出:

[[ 20.   0.  60.   0. 100.]
 [  0.   0.   0.   0.   0.]
 [ 50.   0.  54.   0.  58.]
 [  0.   0.   0.   0.   0.]]
解决方案

方法1:直接使用NumPy切片赋值(最优)

NumPy支持多维切片操作,直接对结果数组的目标位置赋值,完全不需要手动维护索引,代码简洁且效率更高:

import numpy as np

basearray = np.array([[10, 20, 30, 40, 50],
             [15, 16, 17, 18, 19],
             [25, 26, 27, 28, 29],
             [35, 36, 37, 38, 39]])

incrementx = 2
incrementy = 2
resultarray = np.zeros_like(basearray, dtype=np.float64)

# 直接对目标切片位置赋值
resultarray[::incrementx, ::incrementy] = basearray[::incrementx, ::incrementy] * 2

print(resultarray)

输出与原代码一致:

[[ 20.   0.  60.   0. 100.]
 [  0.   0.   0.   0.   0.]
 [ 50.   0.  54.   0.  58.]
 [  0.   0.   0.   0.   0.]]

方法2:用enumerate配合步长索引(保留循环逻辑场景)

如果必须使用循环,可通过enumerate遍历步长后的索引,避免手动维护stepx和stepy:

import numpy as np

basearray = np.array([[10, 20, 30, 40, 50],
             [15, 16, 17, 18, 19],
             [25, 26, 27, 28, 29],
             [35, 36, 37, 38, 39]])

incrementx = 2
incrementy = 2
resultarray = np.zeros_like(basearray, dtype=np.float64)

# 遍历行索引和对应的行
for i, row in enumerate(basearray[::incrementx]):
    # 遍历列索引和对应的元素
    for j, val in enumerate(row[::incrementy]):
        resultarray[i*incrementx][j*incrementy] = val * 2

print(resultarray)

此方法通过i*incrementx和j*incrementy直接计算目标位置,无需手动更新索引变量,比原代码更简洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:45:36