Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]]

I would like to merge this either into one long list

li2 = [0,1,2,3,4,5,6,7,8]

or into a string with separators:

s = "0,1,2,3,4,5,6,7,8"

Really, I'd like to know how to do both.

like image 303
Sam McAfee Avatar asked Sep 19 '08 17:09

Sam McAfee


People also ask

How do you access the elements of a 2D list in python?

In Python, we can access elements of a two-dimensional array using two indices. The first index refers to the indexing of the list and the second index refers to the position of the elements. If we define only one index with an array name, it returns all the elements of 2-dimensional stored in the array.

How do I turn a list into a string in python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.


2 Answers

Like so:

[ item for innerlist in outerlist for item in innerlist ]

Turning that directly into a string with separators:

','.join(str(item) for innerlist in outerlist for item in 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:

for innerlist in outerlist:
    for item in innerlist:
        ...
like image 184
Thomas Wouters Avatar answered Sep 22 '22 13:09

Thomas Wouters


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:

import itertools
li2 = list(itertools.chain(*li))

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

s = ",".join(itertools.chain(*li))
like image 23
Allen Avatar answered Sep 20 '22 13:09

Allen