简体   繁体   English

如何访问另一个列表中每个列表的第n个元素?

[英]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] 之前在Matlab进行过很多编程,我尝试过l[:][1]但是返回了我[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 : 使用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. 自从您提到Matlab以来,我将提到执行此操作的方法。 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: 这实际上可能更接近于您想要的,并且,如果您打算像很多事情一样使用Matlab,最好早点开始使用numpy:

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. 因此,是的,有一个额外的步骤可以将numpy数组转换为多余的数组,但是您可能希望继续使用数组而不是使用列表,因为它提供了很多额外的功能。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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