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
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. 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:
[[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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.