python - 如何通过引用而不是按值复制列表的单个元素?
问题描述
假设我们有二维数组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 或其他包是否有这种行为?编辑:我想避免编写仅提取列的“包装器”函数。如果我对列进行多次处理,我不想在每次要对列进行操作时生成一个代表列的新列表。
解决方案
所以你有一些超级复杂的代码,但你真正需要的是一个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)
推荐阅读
- php - 无法使用 json_decode 解码 json 变量
- python - Python Paho MQTT:如果充斥着 mqtt 消息,代理没有响应?
- java - 检查ZIP文件是否为空的方法?
- paypal - 是否可以暂停 Paypal 订阅并重新开始备份,它停止的地方
- c - C 程序在刷新 IO 缓冲区后仍然会丢失一些输出
- javascript - 仅在一个元素上工作来滚动窗口
- cordova-plugins - 无法使用 inAppBrowser 在 Corodva iOS 中加载本地 html 文件
- reactjs - 为什么即使从 bootstrap4-react 导入 BImg 后,我的图像也没有显示在浏览器中?
- python - 创建带单引号和双引号的字符串
- docker - 如何配置 Prometheus consul_sd_configs 使用 https 进行服务