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

James Kew james.kew at btinternet.com
Sun Sep 8 15:47:55 EDT 2002


<jubafre at brturbo.com> wrote in message
news:mailman.1031507832.24527.python-list at python.org...
> I have a list of lists like this:
>
> labels=[['D1'], ['D2'], ['D3']]
>
> and i want to transform ia a list of strings
>
> labels2==[ 'D1' ,  'D2' ,  'D3' ] <<<<<<<----------- how i can get it????
>

Troels' answers are good if what is required is a list of the first items in
all sub-lists. But it's possible the OP actually wants to produce a
concatenation of all sub-lists:

labels1 = [["D1"], ["D2"], ["D3", "D4"]] --> labels2 == ["D1", "D2", "D3",
"D4"]

Normally I'd write this as:

labels2 = []
for sublist in labels1:
    labels2 += sublist

but a quick shufti at the built-in functionals and the lambda form, both of
which I've been shy of up to now, suggests also the one-liner:

labels2 = reduce(lambda x, y: x+y, labels1)

Can this be written in list comprehension form? Can't quite see one at the
moment...

--
James Kew
james.kew at btinternet.com






More information about the Python-list mailing list