3

so say I have a list of lists

x = [['#', '#', '#', '#', '#'], ['#', '0', ' ', ' ', '#'], ['#', '#', '#', ' ', '#']]

Say I need to split this into 3 rows of strings, how do i do this?

Here is how I can do it BUT it is not scalable, say i had tons more lists, then I would have to write so many print statments. I thought about a for statment

print "".join(mlist[0])
print "".join(mlist[1])
print "".join(mlist[2])

I was thinking about something like this but it didn't work

zert = ""
total = 0
for a in mlist:
     for b in a:
        if total < 6:
            print zert
            total = 0
            zert = ''
        zert += b

        total += 1

^ the problem above is that i would need to save a first, then iterate over it BUT just checking if there is not an inbuilt function? I tried ''.join(mlist) but that does work since its lists in a list?

Is there a simpler way to do this?

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
Ghozt
  • 257
  • 3
  • 13

4 Answers4

4

You can use a list comprehension to join lists:

print '\n'.join([''.join(inner) for inner in mlist])

The list comprehension creates a string of each nested list, then we join that new list of rows into a larger string with newlines.

Demo:

>>> mlist = [['#', '#', '#', '#', '#'], ['#', '0', ' ', ' ', '#'], ['#', '#', '#', ' ', '#']]
>>> print '\n'.join([''.join(inner) for inner in mlist])
#####
#0  #
### #

You could also have used a for loop:

for inner in mlist:
    print ''.join(inner)
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
1
>>> orig_list = [['#', '#', '#', '#', '#'], ['#', '0', ' ', ' ', '#'], ['#', '#', '#', ' ', '#']]
>>> new_list = [ "".join(x) for x in orig_list ]
>>> new_list
['#####', '#0  #', '### #']
>>> print("\n".join(new_list))
#####
#0  #
### #
DhruvPathak
  • 40,405
  • 15
  • 109
  • 170
1

Working with what you have so far, to just directly print it.

for a in mlist:
  print "".join(a)  
doctorlove
  • 18,125
  • 2
  • 46
  • 59
1

or most simply

for a in x:
    print "".join(a)
brainovergrow
  • 458
  • 3
  • 13