【问题标题】:Cython - iterate through mapCython - 遍历地图
【发布时间】: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

【问题讨论】:

    标签: python cython


    【解决方案1】:

    地图迭代器没有元素firstsecond。相反,它有一个operator*,它返回一个pair 引用。在 C++ 中,您可以使用 it->first 一次性完成此操作,但该语法在 Cython 中不起作用(在这种情况下,决定使用 -> 而不是 . 本身还不够智能)。

    改为使用cython.operator.dereference:

    from cython.operator cimport dereference
    
    # ...
    
    print(dereference(it).first)
    

    同样,it++ 可以用 cython.operator.postincrement 完成

    【讨论】:

    • 感谢您的快速回答!它正在工作,我正在编辑帖子。
    猜你喜欢
    • 2011-03-23
    • 2011-12-22
    • 1970-01-01
    • 2022-01-13
    • 2015-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多