boostpython3在dict上迭代
我使用(Python 2.7)以这种方式迭代boostpython3在dict上迭代,python,c++,dictionary,boost,Python,C++,Dictionary,Boost,我使用(Python 2.7)以这种方式迭代dict: boost::python::list myList = myDict.items(); for(int i = 0; i < len(myList); i++) { pytuple pair = extract<pytuple>(itemsView[t]); string memberKey = extract<string>(pair[0]); object member =
dict
:
boost::python::list myList = myDict.items();
for(int i = 0; i < len(myList); i++)
{
pytuple pair = extract<pytuple>(itemsView[t]);
string memberKey = extract<string>(pair[0]);
object member = pair[1];
}
boost::python::list myList=myDict.items();
for(int i=0;i
但是升级到3.7items()
后,将不再返回列表,而是返回一个视图
,该视图只有在对其进行迭代后才会具体化
如果我尝试从items()
初始化列表,它会失败,并说TypeError:应该是list类型的对象;取而代之的是dict_items类型的对象
如何使用BoostPython迭代Python3+dict
或者,
如何将词典转换为列表?扩展Ernest的注释答案是将
视图转换为列表:
auto myList = list(myDict.items());
如果是代理词典,则需要执行以下操作:
auto myList = list(call_method<object>(myProxyDict.ptr(), "items"));
auto myList=list(调用_方法(myProxyDict.ptr(),“items”);
您也可以采用这种方法
boost::python::list keys = boost::python::list(global.keys());
for (int i = 0; i < len(keys); ++i) {
boost::python::extract<std::string> extractor(keys[i]);
if (extractor.check()) {
std::string key = extractor();
// access the dict via global[key] to the value
}
}
boost::python::list keys=boost::python::list(global.keys());
对于(int i=0;i
另一种方式:
object theIterable = theObjectDict.keys();
object theIterator = theIterable.attr("__iter__")();
do
{
try
{
object theKey = theIterator.attr("__next__")();
std::string memberkey = extract< std::string >( theKey );
}
catch(...)
{
PyObject*theError = PyErr_Occurred();
if( theError )
{
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
if( ptype == PyExc_StopIteration )
{
PyErr_Clear();
break;
}
}
throw;
}
} while(1);
object Iterable=对象dict.keys();
对象Iterator=Iteratable.attr(“'iter')();
做
{
尝试
{
对象theKey=iterator.attr(“\uu next\uu”)();
std::string memberkey=extract(theKey);
}
捕获(…)
{
PyObject*theError=PyErr_出现();
如果(错误)
{
PyObject*ptype、*pvalue、*ptraceback;
PyErr_Fetch(&ptype,&pvalue,&ptraceback);
if(ptype==PyExc\u StopIteration)
{
PyErr_Clear();
打破
}
}
投
}
}而(1),;
您不能使用强制转换为列表(dict.items())吗?这很有效。发生的情况是,这个错误来自另一个地方,在那里我尝试做类似的事情,但这次是在代理目录中。有没有办法解决下一个问题?我现在的做法是:call_方法(proxyDict.ptr(),“items”)假设你给出了答案,你现在已经解决了。无论如何,我很乐意帮忙:)我已经在