Reputation: 17
Is there a way to write the code below in an easier way? The code:
lista = []
for i in range(5):
lista.append([]) # >>> [[], [], [], [], []]
l25 = []
for i in range(1, 26):
l25.append(str(i).zfill(2))
part = 5
k = 0
while k < len(lista):
lista[k] = l25[part-5:part]
k = k + 1
part = part + 5
i = 0
while i < len(lista):
print(*lista[i], sep=" ")
i = i + 1
I want to use a nested list with several lists into.
The code above will print:
01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Upvotes: 2
Views: 186
Reputation: 12990
You can build your grid with a list comprehension and then print it:
grid = [[str(i).zfill(2) for i in range(j, j + 5)] for j in range(1, 26, 5)]
for line in grid:
print(' '.join(line))
Output
01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Upvotes: 6
Reputation: 61910
You could use itertools.count:
from itertools import count
counter = count(1)
lista = [[str(next(counter)).zfill(2) for j in range(5)] for i in range(5)]
i = 0
while i < len(lista):
print(*lista[i], sep=" ")
i = i + 1
Output
01 02 03 04 05
06 07 08 09 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Upvotes: 2