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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Ghozt
  • 267
  • 4
  • 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
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • I think you can use a generator expression here, can't you? `'\n'.join(''.join(inner) for inner in mlist)` – Benjamin Hodgson Aug 15 '13 at 11:51
  • @poorsod: Yes, but that is slower than using a list comprehension. See [list comprehension without \[ \], Python](http://stackoverflow.com/q/9060653) – Martijn Pieters Aug 15 '13 at 11:52
  • @MartijnPieters Thanks for the link! Is `join` the only case where the list comp is faster than the generator exp? – Benjamin Hodgson Aug 15 '13 at 11:55
  • 1
    @poorsod: `str.join()` is a specific case where using a list comp is better, because `str.join()` **has** to use a list internally (it iterates over the strings twice, once to calculate the output length, and a second time to build the string). – Martijn Pieters Aug 15 '13 at 11:57
  • @poorsod: In most cases, avoiding having to build a list is better. – Martijn Pieters Aug 15 '13 at 11:57
1
>>> orig_list = [['#', '#', '#', '#', '#'], ['#', '0', ' ', ' ', '#'], ['#', '#', '#', ' ', '#']]
>>> new_list = [ "".join(x) for x in orig_list ]
>>> new_list
['#####', '#0  #', '### #']
>>> print("\n".join(new_list))
#####
#0  #
### #
DhruvPathak
  • 42,059
  • 16
  • 116
  • 175
1

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

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

or most simply

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