繁体   English   中英

在 Python 中嵌套 for 循环 - 创建二维数组/列表列表

[英]Nested for Loops in Python- creating a two dimensional array/list of lists

这里是 Python 的新手。 我只需要对下面的输出中的第一个“列表列表”如何全部为 0 进行一些说明……循环的第一次迭代是第零次迭代吗?

#collect input from the user as integers

X=int(input("Enter a Value for 'X': "))
Y=int(input("Enter a Value for 'Y': "))
print("")
#define the outermost list as an empty list
outerlist=[]
#outermost loop should control the outermost list
#create that one first...outerlist
for i in range (X):
    #now create the innerlist
    innerlist=[]
    #append the innerlist 'Y' number of times
    for j in range(Y):

        innerlist.append(i*j)
    outerlist.append(innerlist)

print(outerlist)

输出:

问题 1:

Enter a Value for 'X': 3
Enter a Value for 'Y': 5

[[0, 0, 0, 0, 0], [0, 1, 2, 3, 4], [0, 2, 4, 6, 8]]

因为range(N)函数默认从 0 迭代到N-1 要从 1 迭代到 N,您应该具有起始值和结束值。 例如range(1, N+1)将从 1 迭代到 N。

我已将您的代码更正如下:

# collect input from the user as integers

X = int(input("Enter a Value for 'X': "))
Y = int(input("Enter a Value for 'Y': "))
print("")
# define the outermost list as an empty list
outerlist = []
# outermost loop should control the outermost list
# create that one first...outerlist
for i in range(1, X + 1):
    # now create the innerlist
    innerlist = []
    # append the innerlist 'Y' number of times
    for j in range(1, Y + 1):
        innerlist.append(i * j)
    outerlist.append(innerlist)

print(outerlist)

嵌套循环的工作原理是,从外循环的第一个元素开始,在其中运行整个内循环,完成它,移动到外循环的第二个元素,完成内循环的所有元素等等...

最后一个循环有外循环的大小,以及内循环的元素数量让我举个例子,你的 2 个列表。

Size of X is 3
Size of Y is 5
Goes into X[0] -> Fill that element with the 5 inputs 0 * y[0], then 0 * y[1]... etc
Goes to X[1] -> Fills it with the 5 inputs of 1  * Y[0], then 1 * Y[1] ..
goes into X[2] -> same thing as before

最终列表将是 [ [ 0 y[0], 0 y[1], 0 y[2],0 y[3], 0 y[4] ] , [ 1 y[0], 0 y[1], 0 y[2], 0 y[3], 0 y[4], 0*y[5] ] ...等

暂无
暂无

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

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