简体   繁体   English

numpy 2D 索引 [:,0] 的等效列表列表

[英]List of lists equivalent for numpy 2D indexing [:,0]

I need to access the first element of each list within a list.我需要访问列表中每个列表的第一个元素。 Usually I do this via numpy arrays by indexing:通常我通过 numpy arrays 通过索引来做到这一点:

import numpy as np
nparr=np.array([[1,2,3],[4,5,6],[7,8,9]])
first_elements = nparr[:,0]

b/c:公元前:

print(nparr[0,:])
[1 2 3]
print(nparr[:,0])
[1 4 7]

Unfortunately I have to tackle non-rectangular dynamic arrays now so numpy won't work.不幸的是,我现在必须处理非矩形动态 arrays 所以 numpy 将无法工作。

But Pythons standard lists behave strangely (at least for me):但是 Python 的标准列表表现得很奇怪(至少对我来说):

pylist=[[1,2,3],[4,5,6],[7,8,9]]
print(pylist[0][:])
[1, 2, 3]
print(pylist[:][0])
[1, 2, 3]

I guess either lists doesn't support this (which would lead to a second question: What to use instead) or I got the syntax wrong?我猜要么列表不支持这一点(这将导致第二个问题:改用什么)或者我的语法错误?

You have a few options.你有几个选择。 Here's one.这是一个。

pylist=[[1,2,3],[4,5,6],[7,8,9]]
print(pylist[0])                  # [1, 2, 3]
print([row[0] for row in pylist]) # [1, 4, 7]

Alternatively, if you want to transpose pylist (make its rows into columns), you could do the following.或者,如果您想转置pylist (将其行转换为列),您可以执行以下操作。

pylist_transpose = [*zip(*pylist)]
print(pylist_transpose[0])        # [1, 4, 7]

pylist_transpose will always be square with a number of rows equal to the length of the shortest row in pylist . pylist_transpose将始终是正方形,行数等于pylist中最短行的长度。

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

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