Splitting a nested list into two lists [duplicate]

2020-02-26 07:17发布

问题:

I have a nested list like this:

    my_list = [[1320120000000, 48596281], [1320206400000, 48596281], [1320292800000, 50447908]]

I would like to split it into something that looks like this:

    my_list1 = [48596281, 48596281, 50447908] 
    my_list2 = [1320120000000, 1320206400000, 1320292800000]    

I know that this is fairly simple, but I haven't been able to get it to work. Any help would be much appreciated.

回答1:

This is what the builtin function zip is for.

my_list2, my_list1 = zip(*my_list)

If you want lists instead of tuples, you can do

my_list2, my_list1 = map(list, zip(*my_list))


回答2:

You can use list comprehension.

my_list1 = [i[1] for i in my_list]
my_list2 = [i[0] for i in my_list]


回答3:

using list comprehension:

In [6]: lis1,lis2=[x[0] for x in my_list],[x[1] for x in my_list]
In [7]: lis1
Out[7]: [1320120000000L, 1320206400000L, 1320292800000L]

In [8]: lis2
Out[8]: [48596281, 48596281, 50447908]

or using operator.itemgetter():

In [19]: lis1,lis2=map(itemgetter(0),my_list) , map(itemgetter(1),my_list)

In [20]: lis1
Out[20]: [1320120000000L, 1320206400000L, 1320292800000L]

In [21]: lis2
Out[21]: [48596281, 48596281, 50447908]

timeit comparisons:

In [42]: %timeit lis1,lis2=[x[0] for x in my_list],[x[1] for x in my_list]  #winner if lists are required
100000 loops, best of 3: 1.72 us per loop

In [43]: %timeit my_list2, my_list1 = zip(*my_list) # winner if you want tuples
1000000 loops, best of 3: 1.62 us per loop

In [44]: %timeit my_list2, my_list1 = map(list, zip(*my_list))
100000 loops, best of 3: 4.58 us per loop

In [45]: %timeit lis1,lis2=map(itemgetter(0),my_list),map(itemgetter(1),my_list)
100000 loops, best of 3: 4.4 us per loop