【问题标题】:Using Py_BuildValue() to create a list of tuples in C使用 Py_BuildValue() 在 C 中创建元组列表
【发布时间】:2016-07-03 05:17:24
【问题描述】:

我正在尝试使用Py_BuildValue() 在 C 中创建元组列表。

我正在尝试构建的内容如下所示:

[ (...), (...), ... ] 

我不知道编译时要创建的元组数量,所以我不能在这里使用一些静态数量。

基本上使用带有一个元组的Py_BuildValue(),这就是代码的样子:

PyObject * Py_BuildValue("[(siis)]", name, num1, num2, summary);

但这仅适用于一个元组。我需要在列表中有多个可以通过 for 循环添加的元组。我怎样才能做到这一点?

【问题讨论】:

    标签: python c pyobject


    【解决方案1】:

    您可以使用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) {
            // ...
        }
    }
    

    这将创建一个表单列表...

    [(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11), (12, 13, 14, 15)]
    

    【讨论】:

    • 是否有理由使用PyLongPyInt?如我的示例中所示,我有一些整数,它们是num1num2。它们并不长,但我假设有一个原因我仍然想像你使用的那样使用PyLong?对于空终止的char * string,我想使用哪个函数?查看文档有很多我可以使用的PyString 版本。
    • @Fogest:在 CPython 3 上,PyInt 不再存在,所有整数都由 PyLong 对象表示。
    • 啊,谢谢你的解释。 PyString 领域是否有类似的案例,还是我应该只选择一个适合我的案例?
    • 您可能希望在过渡到 CPython 3 时查看 the list of changes in the API。有一个完整的字符串部分,其中发生了很大变化。
    • 哇,听起来 CPython3 中没有 PyString。好的,我会考虑使用PyUnicode。感谢您的帮助,我已经接受了您的回答,因为它确实解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-29
    • 2016-01-10
    • 2021-08-16
    • 2022-01-12
    相关资源
    最近更新 更多