'How to print a nested list like a grid?
l1 = [[" "], [" "], [" "], [" "],
[" "], [" "], [" "], [" "],
[" "], [" "], [" "], [" "],
[" "], [" "], [" "], [" "]]
As you can see I want these 16 empty "boxes" To have an output of 4x4. I tried to search Stack Overflow and the web for solutions to this. But nothing seems to work, as the questions regarding nested lists mostly have to do with integers.
Desired output:
[" "][" "][" "][" "]
[" "][" "][" "][" "]
[" "][" "][" "][" "]
[" "][" "][" "][" "]
Or:
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[ ][ ][ ][ ]
[ ][ ][ ][ ]
Solution 1:[1]
How about this.
code
l1 = [[" "], [" "], [" "], [" "],
[" "], [" "], [" "], [" "],
[" "], [" "], [" "], [" "],
[" "], [" "], [" "], [" "]]
for i, e in enumerate(l1):
if (i+1)%4 != 0:
print(e, end='') # print box without new line
else:
print(e)
Output
[' '][' '][' '][' ']
[' '][' '][' '][' ']
[' '][' '][' '][' ']
[' '][' '][' '][' ']
Solution 2:[2]
if you know the original size you can use nested fors to print this
for i in range(4):
for j in range(4):
print(l1 [ i*4 + j] ,end='')
print("")
Solution 3:[3]
I want to print out my 2d map in the console.
Here is what I did.
Code
if __name__ == "__main__":
chunk = [
["61", "61", "61", "61"],
["61", "61", "61", "61"],
["61", "61", "61", "61"],
["61", "61", "61", "61"],
]
print(*chunk, sep="\n")
Output
['61', '61', '61', '61']
['61', '61', '61', '61']
['61', '61', '61', '61']
['61', '61', '61', '61']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | ferdy |
Solution 2 | |
Solution 3 | achang |