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.
Try that:
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:
To make it a flattened list use either:
Then,
join
to make it a string.My favorite, and the shortest one, is this:
and
EDIT: use
sum
instead ofreduce
, (thanks Thomas Wouters!)There's a couple choices. First, you can just create a new list and add the contents of each list to it:
Alternately, you can use the
itertools
module'schain
function, which produces an iterable containing all the items in multiple iterables:If you take this approach, you can produce the string without creating an intermediate list:
For the second one, there is a built-in string method to do that :
For the first one, you can use join within a comprehension list :
But it's easier to use itertools.flatten :
N.B : itertools is a module that help you to deal with common tasks with iterators such as list, tuples or string... It's handy because it does not store a copy of the structure you're working on but process the items one by one.
EDIT : funny, I am learning plenty of way to do it. Who said that there was only one good way to do it ?