我想用来Py_BuildValue()在C中创建一个元组列表.
我想要构建的内容如下所示:
[ (...), (...), ... ]
Run Code Online (Sandbox Code Playgroud)
我不知道在编译时创建的元组数量,所以我不能在这里使用一些静态数量.
Py_BuildValue()这里基本上使用一个元组是代码的样子:
PyObject * Py_BuildValue("[(siis)]", name, num1, num2, summary);
Run Code Online (Sandbox Code Playgroud)
但那只会是一个元组.我需要在列表中有多个元组,我可以通过for循环添加.我怎么能做到这一点?
您可以使用PyList_New(),PyTuple_New(),PyList_Append(),和PyTuple_SetItem()做到这一点...
const Py_ssize_t tuple_length = 4;
const unsigned some_limit = 4;
PyObject *my_list = PyList_New(0);
if(my_list == NULL) {
// ...
}
for(unsigned i = 0; i < some_limit; i++) {
PyObject *the_tuple = PyTuple_New(tuple_length);
if(the_tuple == NULL) {
// ...
}
for(Py_ssize_t j = 0; i < tuple_length; i++) {
PyObject *the_object = PyLong_FromSsize_t(i * tuple_length + j);
if(the_object == NULL) {
// ...
}
PyTuple_SET_ITEM(the_tuple, j, the_object);
}
if(PyList_Append(my_list, the_tuple) == -1) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
这将创建一个表单列表......
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)]
Run Code Online (Sandbox Code Playgroud)