How Can I Print A One Dimensional Array As Grid In Python?
I have an array of 200 items. grid = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 .... and so on] How can I print it as a 2D array like so? Split it every 10 characters actually. 0,
Solution 1:
Here is a simple solution using slicing:
a = [0 for i in range(200)]
for i in range(len(a) // 10):
sub_list = a[i * 10:(i + 1) * 10]
print(', '.join(map(str, sub_list)))
Although this can be compressed to a single line with some list comprehensions, it would then become very hard to understand.
Solution 2:
You can iterate of the length of grid
, in this case 200
by 10
and use that as the start for your slicing, printing that plus 9 additional values.
grid = [0]*200
for x in range(0,len(grid),10):
print(grid[x:x+9])
edit: This will print slices of the list, which is still a list which is why you see the brackets. Like others have shown you can use join and map to print it as a comma separated string if you really need to:
grid = [0]*200
for x in range(0,len(grid),10):
print(','.join(map(str,grid[x:x+9])))
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, 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, 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, 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, 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, 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, 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, 0, 0, 0, 0, 0]
Solution 3:
Try this:
row_length = 10
for row in [grid[i:i + row_length] for i in range(0, len(grid), row_length)]:
print(row)
Solution 4:
grid = [0]*200
print(*[grid[i:i+10] for i in range(0, len(grid), 10)], sep='\n')
[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, 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]
[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, 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]
[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, 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]
[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, 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]
Solution 5:
Simple and compact solution, without any external references and exatly your stated output:
for s in [[n for n in grid[i:i+10]] for i in range(0, len(grid), 10)]:
print(str(s)[1:-1]+',')
Post a Comment for "How Can I Print A One Dimensional Array As Grid In Python?"