在我的模块中,有一个方法可以获取python列表并将其除以双精度
static PyObject *st_div_r(PyObject *self, PyObject *args){
PyObject *pList;
Py_ssize_t n;
double x;
int i;
if (!PyArg_ParseTuple(args, "O!d", &PyList_Type, &pList, &x)) {
PyErr_SetString(PyExc_TypeError, "parameters are wrong.");
return NULL;
}
n = PyList_Size(pList);
for(i=0;i<n;i++)
{
PyList_SetItem(pList,i,Py_BuildValue("d",PyFloat_AsDouble(PyList_GetItem(pList,i))/x));
};
Py_INCREF(pList);
return pList;
}
它是这样工作的
my_mod.st_div_r([1,2,3],0.5)
[2,4,6]
我想在模块中的另一个方法中使用st_div_r,该方法获取列表列表,将其第一个元素除以双精度,然后返回它
static PyObject *det(PyObject *self, PyObject *args){
PyObject *pList;
double d = 2.0;
if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &pList)) {
PyErr_SetString(PyExc_TypeError, "parameters are wrong.");
return NULL;
}
PyList_SetItem(pList,0,st_div_r(pList,(PyList_GetItem(pList,0),Py_BuildValue("d",d))));
Py_INCREF(pList);
return pList;
}
它应该是这样工作的
my_mod.det([[1,2],[3,4]])
[[0.5,1],[3,4]]
但这不管用
TypeError: parameters are wrong
因此,问题是如何在det中调用st_div_r,以及作为self传递什么。都会很感谢你的帮助。谢谢
发布于 2020-04-30 12:57:54
您必须创建一个PyTuple作为您自己的函数(St_div_r)的第二个参数!
有两种主要的方法可以做到这一点!
第一种方法
PyObject *first_list = PyList_GetItem(pList, 0)
//PyObject *divider = Py_BuildValue("d", d)
//PyObject *tuple_with_list_and_divider = Py_BuildValue("(Od)", first_list, divider);
PyObject *tuple_with_list_and_divider = Py_BuildValue("(Od)", first_list, d);
PyObject *list_after_division = st_div_r(pList, tuple_with_list_and_divider)
PyList_SetItem(pList , 0, list_after_division);
第二种方式
PyObject *first_list = PyList_GetItem(pList, 0)
PyObject *divider = Py_BuildValue("d", d)
PyObject *tuple_with_list_and_divider = PyTuple_New(2);
PyTuple_SetItem(tuple_with_list_and_divider, 0, first_list);
PyTuple_SetItem(tuple_with_list_and_divider, 1, divider);
PyObject *list_after_division = st_div_r(pList, tuple_with_list_and_divider)
PyList_SetItem(pList , 0, list_after_division);
在第一个示例中,我忘记了Py_BuildValue将d转换为Py_Double。
很抱歉我的英语不好!
https://stackoverflow.com/questions/61462137
复制相似问题