Skip to content Skip to sidebar Skip to footer

How Do I Merge A 2d Array In Python Into One String With List Comprehension?

List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: li = [[0,1,2],[3,4,5],[6,7,8]]

Solution 1:

Like so:

[ item forinnerlistin outerlist foritemin innerlist ]

Turning that directly into a string with separators:

','.join(str(item) forinnerlistin outerlist foritemin innerlist)

Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:

forinnerlistin outerlist:
    foritemin innerlist:
        ...

Solution 2:

There's a couple choices. First, you can just create a new list and add the contents of each list to it:

li2 = []
for sublist in li:
    li2.extend(sublist)

Alternately, you can use the itertools module's chain function, which produces an iterable containing all the items in multiple iterables:

importitertoolsli2= list(itertools.chain(*li))

If you take this approach, you can produce the string without creating an intermediate list:

s = ",".join(itertools.chain(*li))

Solution 3:

Try that:

li=[[0,1,2],[3,4,5],[6,7,8]]
li2 = [ y for x in li for y in x]

You can read it like this: Give me the list of every ys. The ys come from the xs. The xs come from li.

To map that in a string:

','.join(map(str,li2))

Solution 4:

My favorite, and the shortest one, is this:

li2 = sum(li, [])

and

s = ','.join(li2)

EDIT: use sum instead of reduce, (thanks Thomas Wouters!)

Solution 5:

import itertools
itertools.flatten( li )

Post a Comment for "How Do I Merge A 2d Array In Python Into One String With List Comprehension?"