gpt4 book ai didi

python - 将列表列表从 Python 传递到 C 作为 uint64_t 矩阵

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:37 28 4
gpt4 key购买 nike

如何生成数字列表(C 中的 uint64_t)例如:a = [[1, 5, 9], [4, 6, 7], [8, 2, 3]] 作为 C 程序的参数传递(通过 argv),然后作为二维矩阵在 C 程序中打印(或能够访问该数据)?

在我的 C 程序中,我使用 unint64_t 类型的非预定义大小矩阵 (uint64_t matrix[nrows][ncols])

最佳答案

有很多方法可以做到这一点,但最简单的可能就是先展平矩阵:

def flatten(a):
yield len(a)
cols = max(len(i) for i in a)
yield cols
for i in a:
for j in i:
yield j
for j in range(0, cols - len(i)):
yield 0

然后您可以使用它的结果将参数提供给您的 C 程序,然后您可以从中构建矩阵(需要 C99):

#include <stdlib.h>
#include <inttypes.h>

void load_matrix(uint64_t *matrix, char **p, int alen) {
while (alen-- > 0)
*matrix++ = atoi(*p++);
}

void do_work(uint64_t matrix[nrows][ncols], int nrows, int ncols) {
...
}

int main(int argc, char **argv) {
int nrows = atoi(argv[1]), ncols = atoi(argv[2]);

// check ncols and nrows and argc
...

uint64_t *matrix;
matrix = malloc(nrows * ncols * sizeof(*matrix));

// check matrix isn't NULL
...

load_matrix(matrix, argv + 3, nrows * ncols);
do_work(matrix, nrows, ncols);
...
}

请记住,这只是一个示例,即 atoi 之类的内容并不合适。

如果你想使用 C89,你需要处理一个平面数组,结果是一样的。

但是,如果矩阵很大,您真的不需要那样;你会以类似的方式序列化它(也许有更有效的实现),但你会想直接处理二进制数据,并通过共享内存、文件、套接字或管道将其传递给你的 C 程序,所以无需进一步处理。

如果您正在处理一个非常大的数据集,那么您肯定希望在 Python 和 C 中使用相同的表示,并且您可能希望使用共享内存或文件。

关于python - 将列表列表从 Python 传递到 C 作为 uint64_t 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46306031/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com