Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print out a 2d list that is formatted into a grid?

Tags:

python

list

2d

Currently, I have made this code

def grid_maker(h,w):
    grid = [[["-"] for i in range(w)] for i in range(h)]
    grid[0][0] = ["o"]
    print grid

>>>grid_maker(3,5) => [[['o'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']]] 

I want to make another function that will take in the produced 2d array and print it out such that it is in this format:

o----
-----
----- 

However, I am unsure where to start.

like image 638
user3225528 Avatar asked Oct 21 '25 21:10

user3225528


1 Answers

If you want to "pretty" print your grid with each sublist on its own line, you can use pprint:

>>> grid=[[['o'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']], [['-'], ['-'], ['-'], ['-'], ['-']]]

>>> from pprint import pprint
>>> pprint(grid)

[[['o'], ['-'], ['-'], ['-'], ['-']],
 [['-'], ['-'], ['-'], ['-'], ['-']],
 [['-'], ['-'], ['-'], ['-'], ['-']]]

It will still show each element as a list, as you defined it, if you want to show them as strings you'll have to use joins like m.wasowski suggests.

like image 66
anana Avatar answered Oct 23 '25 11:10

anana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!