首页 > 解决方案 > 如何通过引用而不是按值复制列表的单个元素?

问题描述

假设我们有二维数组foo_arr

foo_arr = [[None, None, None, None],
           [None, None, None, None],
           [None, None, None, None],
           [None, None, None, None]]

现在,我希望能够从其行列访问 2D 数组。例如,我可以做row_0 = foo_arr[0],任何更改foo_arr[0]都会反映在row_0; 即如果我们这样做:

row_0 = foo_arr[0]
foo_arr[0][0] = (0, 0)
# row_0 == [(0, 0), None, None, None]

我也希望能够用列做到这一点。例如,我想要类似 的东西column_0 = [foo_arr[0][0], foo_arr[1][0], foo_arr[2][0], foo_arr[3][0]],当我更改foo_arr(或column_0)时,他们应该都能看到。所需行为的说明:

column_0 = [foo_arr[i][0] for i in range(4)]
foo_arr[0][0] = (0, 0)
foo_arr[1][0] = (0, 1)
# Desired: column_0 == [(0, 0), (0, 1), None, None]
# Actual: column_0 == [None, None, None, None]

本质上,我想要这样,用 C 语言编写:

int** foo_arr = malloc(sizeof(int*)*4);
for(int i=0; i<4; i++) {
    foo_arr[i] = malloc(sizeof(int)*4);
    for(int j=0; j<4; j++) {
        foo_arr[i][j] = -1; /* Using -1 here to represent None */
    }
}
int* row_0 = foo_arr[0];
int** column_0 = malloc(sizeof(int)*4);
for(int i=0; i<4; i++) {
    column_0[i] = &foo_arr[i][0]; /* Yes, technically the same as just doing foo_arr[i] for column 0 */
}
/* Changing the 2D array: */
foo_arr[0][0] = 0;
foo_arr[1][0] = 4;
foo_arr[2][0] = 8;
/* We should have:
   *column_0[0] == 0;
   *column_0[1] == 4;
   *column_0[2] == 8; */

是否有可能在 Python 中获得这种行为?numpy 或其他包是否有这种行为?编辑:我想避免编写仅提取列的“包装器”函数。如果我对列进行多次处理,我不想在每次要对列进行操作时生成一个代表列的新列表。

标签: pythonarrayslist

解决方案


所以你有一些超级复杂的代码,但你真正需要的是一个numpy数组

import numpy as np

# foo_arr = np.array(
#     [
#         [None, None, None, None],
#         [None, None, None, None],
#         [None, None, None, None],
#         [None, None, None, None]
#     ]
# )
# or better:
foo_arr = np.empty((4, 4), dtype=object)

row_0 = foo_arr[0, :]
col_0 = foo_arr[:, 0]

foo_arr[1, 0] = (0, 0)
print(row_0, col_0)

推荐阅读