1

I have a simple list of lists called square:

square = [[1,2,3],[4,5,6],[7,8,9]]

and my goal is to iterate through each of the nine elements and get all the values in that element's row and column simultaneously. In this example, the first iteration (for element 1) should return [1,2,3] and [1,4,7], the second (for element 2) would give me [1,2,3] and [2,5,8], etc. The following code works:

for r in range(3):
    for c in range(3):
        row = square[r]
        col = [square[c1][c] for c1 in range(3)]

but is there another method using base Python to do this?

I can transpose and iterate over the list using for c in zip(*square):, which works if I just need the columns once, but is there no way to use array slicing to index the columns without storing the transpose of the matrix as well as the matrix itself?

Unfortunately, libraries like numpy aren't an option at the moment because they'll need to go through our code review process first, which takes a long time (on the order of six months...). I didn't write the policy or design the procedures, but it's the policy I have to work with at this institution. I already filed the request for numpy, but in the meantime, I'm just using base Python.

4

2 回答 2

4

使用 numpy

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

仅使用 Python

>>> square = [[1,2,3],[4,5,6],[7,8,9]]
>>> square[0]
[1, 2, 3]
>>> zip(*square)[0]
(1, 4, 7)
于 2013-04-23T21:57:46.013 回答
1

如果您想使用标准 Python 执行此操作,您可能想尝试转置列表。然后,您可以正常索引。您可以执行此操作,zip(*square)然后map(list,)将其转回列表:

square = [[1,2,3],[4,5,6],[7,8,9]]

square_transposed = map(list, zip(*square))

然后square[1]会得到你[2,5,8]

如果您想知道 * 运算符在此上下文中的作用,它会将列表解压缩为一系列位置参数。因此 zip 将[1,2,3] [4,5,6] [7,8,9]它们视为[(1, 4, 7), (2, 5, 8), (3, 6, 9)]. 然后最终的映射将元组转换为列表。

于 2013-04-23T21:58:25.363 回答