python - Cython - 遍历地图
问题描述
我想知道这是否可以直接在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 中使用过 map 容器,但是对于这段代码,我试图坚持使用 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
解决方案
地图迭代器没有元素first
和second
. 相反,它有一个operator*
返回pair
引用。在 C++ 中,您可以it->first
一次性完成此操作,但该语法在 Cython 中不起作用(在这种情况下,它还不够聪明,无法决定使用它->
来代替.
它自己)。
相反,您使用cython.operator.dereference
:
from cython.operator cimport dereference
# ...
print(dereference(it).first)
同样,it++
可以用cython.operator.postincrement
推荐阅读
- reporting-services - SSRS 报告订阅历史
- shell - 如何检查是否更新了大 CDN 文件而不在存储库中存储相同的文件且没有数据库?
- python - 基本 django 站点给出错误为“未找到:/nettrack/
- reactjs - 在 bootstrap-react-table-2 中创建/获取全局数据 ID
- python - 将天数转换为日期时间
- capl - linUpdateResponse 与输出 - LIN 模拟节点有何不同?
- tensorflow - 如何手动初始化 TF 1.x LSTMCell 和 dynamic_rnn
- c# - 通过列表值获取字典键
- excel-formula - Averageifs 使用索引匹配动态选择整列进行平均
- ios - 删除插入分组 UITableView 上方的空间