how to separate a list into two lists?

Kabie kabie2011 at gmail.com
Sat Aug 6 19:23:53 CEST 2011


No.

L1, L2 = zip(*L)

2011/8/7 Chris Angelico <rosuav at gmail.com>

> On Sat, Aug 6, 2011 at 6:07 PM, smith jack <thinke365 at gmail.com> wrote:
> > if a list L is composed with tuple consists of two elements, that is
> > L = [(a1, b1), (a2, b2) ... (an, bn)]
> >
> > is there any simple way to divide this list into two separate lists ,
> such that
> > L1 = [a1, a2... an]
> > L2=[b1,b2 ... bn]
> >
> > i do not want to use loop, any methods to make this done?
>
> One easy way is to use list comprehensions. Technically that'll
> involve a loop, but the loop is handled efficiently under the hood.
>
> L1 = [x[0] for x in L]
> L2 = [x[1] for x in L]
>
> Another way would be to construct a dictionary from your list of
> tuples and then use the keys() and values() of that dictionary to form
> your lists (use collections.OrderedDict if the order matters). But I
> think the list comps are the best way.
>
> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110807/4cc45a97/attachment.html>


More information about the Python-list mailing list