Skip to main content
 首页 » 编程设计

python之使用 for 循环将两个变量一起迭代

2025年05月04日13xiaohuochai

我该如何着手做这样的事情?

假设我有一个 x = np.array([1,2,3,4,5]) 的长度为 5 的数组,

for i,j in range(len(x)): 

我希望 i 和 j 一起递增。

这给我一个错误信息:

TypeError                                 Traceback (most recent call last) 
<ipython-input-4-37d0ddc3decf> in <module>() 
----> 1 for i,j in range(len(x)): 
      2     print i,j 
      3  
 
TypeError: only length-1 arrays can be converted to Python scalars 

我需要它的原因是因为我必须在 for 循环内的条件下使用它。比如,y[i][j],我希望它是 0,0 然后是 1,1 等等。

请您参考如下方法:

为什么首先需要 j?如果 j 总是等于 i,就使用 i。不需要第二个变量。