简体   繁体   English

python 2D列表的索引

[英]Indexing of python 2D list

In order to access the second dimension of a 2D numpy array, we could use eg 为了访问二维numpy数组的第二维,我们可以使用例如

A[:,0:9]

How could we do this to a 2D list? 我们如何对2D列表执行此操作?

Wasteful but should work: 浪费但是应该工作:

list(zip(*(list(zip(*A))[0:9])))

Slightly more economical using itertools.isclice : 使用itertools.isclice更加经济:

list(zip(*(itertools.islice(zip(*A), 0, 9))))

Or one could use map and operator.itemgetter : 或者可以使用mapoperator.itemgetter

list(map(operator.itemgetter(slice(0,9)), A))

An array and nested list version: 数组和嵌套列表版本:

In [163]: A=np.arange(12).reshape(3,4)
In [164]: Al = A.tolist()

For sliced indexing, a list comprehension (or mapping equivalent) works fine: 对于切片索引,列表理解(或映射等效)可以正常工作:

In [165]: A[:,1:3]
Out[165]: 
array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])
In [166]: [l[1:3] for l in Al]
Out[166]: [[1, 2], [5, 6], [9, 10]]

For advanced indexing, the list requires a further level of iteration: 对于高级索引,该列表需要进一步的迭代:

In [167]: A[:,[0,2,3]]
Out[167]: 
array([[ 0,  2,  3],
       [ 4,  6,  7],
       [ 8, 10, 11]])

In [169]: [[l[i] for i in [0,2,3]] for l in Al]
Out[169]: [[0, 2, 3], [4, 6, 7], [8, 10, 11]]

Again there are various mapping alternatives. 同样,有多种映射替代方案。

In [171]: [operator.itemgetter(0,2,3)(l) for l in Al]
Out[171]: [(0, 2, 3), (4, 6, 7), (8, 10, 11)]

itemgetter uses tuple(obj[i] for i in items) to generate those tuples. itemgetter使用tuple(obj[i] for i in items)生成那些元组。

Curiously, itemgetter returns tuples for the list index, and lists for slices: 奇怪的是, itemgetter返回用于列表索引的元组,以及用于切片的列表:

In [176]: [operator.itemgetter(slice(1,3))(l) for l in Al]
Out[176]: [[1, 2], [5, 6], [9, 10]]

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

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