[英]5x5 Grid in Python
developers, I want to make a 5x5 grid in python I try this code but I fail to generate my required output here I use abc for while loop 开发人员,我想在python中制作5x5网格,我尝试使用此代码,但在这里我无法生成所需的输出,我在while循环中使用abc
l1 = []
abc = 1
while abc == 5:
for i in range(1,6,1):
l1.append(i)
abc+=1
print(l1)
but its out was only [] 但它的出局只是[]
I want this type of output 我想要这种类型的输出
['0','0','0','0','0']
['0','0','0','0','0']
['0','0','0','0','0']
['0','0','0','0','0']
['0','0','0','0','0']
Your logic is quite confusing since you have a conditional abc == 5
in your while loop, so it will never execute. 您的逻辑非常混乱,因为您的while循环中有条件
abc == 5
,因此它将永远不会执行。 You can generate what you want by: 您可以通过以下方式生成所需的内容:
[[i for i in range(j, j + 5)] for j in range(0, 25, 5)]
so the output will be: 所以输出将是:
[[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14],
[15, 16, 17, 18, 19],
[20, 21, 22, 23, 24]]
in case you want it to start at 1 and finish at 25: 如果您希望它从1开始并在25结束:
[[i for i in range(j, j + 5)] for j in range(1, 26, 5)]
so the output will be: 所以输出将是:
[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20],
[21, 22, 23, 24, 25]]
Update: (based on the output you provided in the question) : 更新:(基于您在问题中提供的输出) :
grid = [[i for i in range(j, j + 5)] for j in range(0, 25, 5)]
for item in grid:
print(item)
Here's my guess as to what I believe you are asking: 关于我相信您在问的问题,这是我的猜测:
>>> l1 = [[i for i in range(1, 6)] for _ in range(5)]
>>> print(*l1, sep='\n')
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
>>>
This print()
idiom is simple enough to memorize and use whenever you're in the Python shell and want to quickly examine a two dimensional list. 这个
print()
用法很简单,足以记住和使用,只要您在Python外壳中并且想要快速检查一个二维列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.