简体   繁体   中英

How to access the nth element of every list inside another list?

This must be a very basic question, so please bear with me. I have a list of lists like this

l = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

I want to access the second value in each list within the outer list as another list

[2, 5, 8, 11]

Is there a one-step way of doing this? Having programmed in Matlab quite a lot before, I tried l[:][1] but that returns me [4, 5, 6]

Use a list comprehension:

>>> lis = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> [ x[1] for x in lis]
[2, 5, 8, 11]

Another way using operator.itemgetter :

>>> from operator import itemgetter
>>> map( itemgetter(1), lis)
[2, 5, 8, 11]

Since you mention Matlab, I'm going to mention the numpy way of doing this. That may actually be closer to what you'd like, and if you're going to use Matlab like things a lot, it's better to start using numpy early:

import numpy
a = numpy.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
>>> a[:,1]
array([ 2,  5,  8, 11])

So yes, there is a conversion step to numpy arrays extra, but possibly you want to continue on with an array, instead of using a list, as it offers lots of extras.

>>> L = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
>>> [item[1] for item in L]
[2, 5, 8, 11]

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