简体   繁体   中英

Accessing given element from each sublist of multidimensional list without for loop

Say I have a list of lists for example:

list0 = [[a, .5, .3], [b, .3, .8], [c, .7, 1.3], [d, 1.03, .2]]

I want to call the second element of each sublist for output to a list I assumed this would work.

input: print(list0[:][1])

output: [b, .3, .8]

but I was hoping to get this instead: (.5, .3, .7, 1.03)

Is there a possible way to call all sublists and access their elements without looping through whole list to create a new one? Can you compare times and describe why we can't call all or a range of sublists to get an element from each without looping through twice, once to get sublists and once to access each of them?

Just use a list comprehension -

second_element_of_each_sublist = [x[1] for x in list0]

or alternatively, use a map coupled with itemgetter -

from operator import itemgetter
second_element_of_each_sublist  = list(map(itemgetter(1), list0))

Avoiding loops altogether isn't gonna happen, at least if you take into account what might be going on behind the scenes. It's just a question of efficiency...

In [196]: list0 = [['a', .5, .3], ['b', .3, .8], ['c', .7, 1.3], ['d', 1.03, .2]]

Some comparative times:

The recommended list comprehension:

In [197]: timeit [l[1] for l in list0]
410 ns ± 17.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Starting with a list version of 'transpose':

In [198]: timeit list(zip(*list0))[1]
661 ns ± 3.63 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Selecting a column from an array:

In [199]: timeit np.array(list0)[:,1]
16 µs ± 177 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The reason numpy questions often ask "without loops", is that Python level iteration on numpy arrays is slow. Where possible we want to use the fast compiled numpy code (which still has loops). But when starting from a list, creating the array is relatively expensive.

Starting with an array, column indexing is fast:

In [200]: %%timeit A = np.array(list0)
     ...: A[:,1]
325 ns ± 11.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Iteration on an array is slower than the same iteration on a list:

In [201]: %%timeit A = np.array(list0)
     ...: [a[1] for a in A] 
5.47 µs ± 96.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

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