简体   繁体   中英

Python list of lists -> make sublists of element n

If I have a list of lists such as:

[[2, 0.84], [2, 0.75], [2, 0.63], [2, 0.6]]

Is there a quick way to get a list of all of the 2nd elements of the inner list? Ie, the example would return:

[0.84, 0.75, 0.63, 0.6]

I'm not entirely sure why this doesn't work:

list[:][0]

But that only return a pair of values in a list.

try:

>>> my_list = [[2, 0.84], [2, 0.75], [2, 0.63], [2, 0.6]]
>>> [item[1] for item in my_list]
[0.84, 0.75, 0.63, 0.6]

Your try list[:][0] does not work, because list[:] makes a copy of list and list[:][0] takes the first sublist of the copy, not first elements of sublists. Also, avoid naming your variables list because it shadows the built-in list .

Here is a solution that gives you the desired output, but as shown in the answer by @Slater Tyranus, it is not the most efficient approach.

In [34]: a = [[2, 0.84], [2, 0.75], [2, 0.63], [2, 0.6]]

In [36]: list(zip(*a)[1])
Out[36]: [0.84, 0.75, 0.63, 0.6]

Hasan is right in the general case, but if you're typically looking for this kind of slicing I would suggest you start using numpy, which is really made for this kind of thing. Specifically:

>>> import numpy as np

>>> my_array = np.array([[2, 0.84], [2, 0.75], [2, 0.63], [2, 0.6]])
>>> my_array[:, 1]
[0.84, 0.75, 0.63, 0.6]

Personally, I find numpy slicing to be much easier to work with, and it seems to align very well with your intuition about the problem above. Also, it's liable to be MUCH faster with large arrays. That said, apparently much slower for arrays at this size, posting timeit results below:

>>> my_list = [[2, 0.84], [2, 0.75], [2, 0.63], [2, 0.6]]
>>> my_array = np.array(my_list)

>>> timeit.timeit("my_array[:, 1]", setup="from __main__ import my_array", number=10000)
0.016569137573242188

>>> timeit.timeit("[item[1] for item in my_list]", setup="from __main__ import my_list", number=10000)
0.006146907806396484

>>> timeit.timeit("list(zip(*my_list)[1])", setup="from __main__ import my_list", number=10000)
0.013128042221069336

Just to show a slightly clearer picture, I ran the results on a larger example to show how these different approaches scale:

>>> my_array = np.random.rand(100,100)
>>> my_list = my_array.tolist()

>>> timeit.timeit("my_array[:, 1]", setup="from __main__ import my_array", number=10000)
0.019372940063476562

>>> timeit.timeit("[item[1] for item in my_list]", setup="from __main__ import my_list", number=10000)
0.07012009620666504

>>> timeit.timeit("list(zip(*my_list)[1])", setup="from __main__ import my_list", number=10000)
1.2308871746063232

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM