【发布时间】:2020-10-23 14:41:35
【问题描述】:
我想知道这是否可以直接在Cython 代码中迭代地图,即, 在.pyx 中。
这是我的例子:
import cython
cimport cython
from licpp.map import map as mapcpp
def it_through_map(dict mymap_of_int_int):
# python dict to map
cdef mapcpp[int,int] mymap_in = mymap_of_int_int
cdef mapcpp[int,int].iterator it = mymap_in.begin()
while(it != mymap.end()):
# let's pretend here I just want to print the key and the value
print(it.first) # Not working
print(it.second) # Not working
it ++ # Not working
这不会编译:Object of type 'iterator' has no attribute 'first'
我之前在 cpp 中使用过地图容器,但是对于这段代码,我试图坚持使用 cython/python,这里可以吗?。
由 DavidW 解决 这是代码的工作版本,遵循 DavidW 的回答:
import cython
cimport cython
from licpp.map import map as mapcpp
from cython.operator import dereference, postincrement
def it_through_map(dict mymap_of_int_int):
# python dict to map
cdef mapcpp[int,int] mymap_in = mymap_of_int_int
cdef mapcpp[int,int].iterator it = mymap_in.begin()
while(it != mymap.end()):
# let's pretend here I just want to print the key and the value
print(dereference(it).first) # print the key
print(dereference(it).second) # print the associated value
postincrement(it) # Increment the iterator to the net element
【问题讨论】: