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

2024-09-30 00:28:25 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是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]]

Tags: the列表forinputvalueascreatelist
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

最后的名单是 [[0y[0],0y[1],0y[2],0y[3],0y[4][1y[0],0y[1],0y[2],0y[3],0y[4],0*y[5]等等

因为默认情况下range(N)函数从零迭代到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)

相关问题 更多 >

    热门问题