简体   繁体   English

嵌套 for 循环的输出 - Python

[英]Output of a Nested for Loop - Python

I am trying to get the output of a nested for loop into an array or matrix.我正在尝试将嵌套for循环的输出放入数组或矩阵中。 For instance, in the code example below, I want to have a (3 by 2)-matrix of the form:例如,在下面的代码示例中,我想要一个 (3 x 2) 形式的矩阵:

[[5 6],
 [6 7],
 [7 8]]

But my code is giving out of bound error.但是我的代码给出了越界错误。

import numpy as np

num = [1,2,3]
sep = [4, 5]
M = np.zeros((3,2))
for i in num:
    for j in sep:
        M[i, j] = i + j
M

However, I realized that changing the initialization to np.zeros((4,6)) seems to work but with some irrelevant cells.但是,我意识到将初始化更改为np.zeros((4,6))似乎有效,但有一些不相关的单元格。 Can someone explain how this works or possibly how I can achieve this (3 by 2)-matrix.有人可以解释这是如何工作的,或者我可能如何实现这个(3 x 2)矩阵。 Nested_Loop

You are using the values in your num and sep lists as indexes.您正在使用numsep列表中的值作为索引。 You need to use indexes instead:您需要改用索引:

import numpy as np

num = [1,2,3]
sep = [4, 5]
M = np.zeros((3,2))
for i_i,i in enumerate(num):
    for i_j,j in enumerate(sep):
        M[i_i, i_j] = i + j

print(M)

Output as required.根据需要输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM