简体   繁体   中英

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:

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.

But Pythons standard lists behave strangely (at least for me):

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_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 .

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