transform a list of lists in a lit of strtings???

Steve Holden sholden at holdenweb.com
Mon Sep 9 16:04:06 EDT 2002


"James Kew" <james.kew at btinternet.com> wrote in message
news:algb9t$1q0jg0$1 at ID-71831.news.dfncis.de...
> "James Kew" <james.kew at btinternet.com> wrote in message
> news:algah9$1p0kp3$1 at ID-71831.news.dfncis.de...
> > labels1 = [["D1"], ["D2"], ["D3", "D4"]]
> > --> labels2 == ["D1", "D2", "D3", "D4"]
>
> > labels2 = reduce(lambda x, y: x+y, labels1)
> >
> > Can this be written in list comprehension form?
>
> Emile's google link suggests (a) flattening is a hoary old chestnut, and
(b)
> yes it can:
>
> labels2 = [i for item in labels1 for i in item]
>
> (I find this oddly hard to read.)
>

This will work if your list structure can contain data items and lists with
data items in them, but it won't flatten a nested list structure of general
complexity. For example:

>>> labels1 = [ [1, 2], [[3, 4, 5], 6], [[[7], 8], 9]]
>>> labels2 = [i for item in labels1 for i in item]
>>> labels2
[1, 2, [3, 4, 5], 6, [[7], 8], 9]

For a complete solution to such a problem you have to use recursion, testing
whether each item you process is composite and recursing to flatten it if
so. This has been discussed so many times before that you should use Google
to find the best way.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list