这里是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]]
嵌套循环的工作原理是,从外部循环的第一个元素开始,在内部,运行整个内部循环,完成它,移动到外部循环的第二个元素,完成内部循环的所有元素,等等
最终循环具有外循环的大小以及内循环中元素的数量 让我举一个例子来说明你的两个清单
最后的名单是 [[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我已将您的代码更正如下:
相关问题 更多 >
编程相关推荐