【问题标题】:Creating c++ maps in a loop in cython在 cython 的循环中创建 c++ 映射
【发布时间】:2017-08-28 23:17:19
【问题描述】:

我正在尝试创建一个 cython 函数,该函数迭代两个 numpy 字符串数组,并根据其中找到的数据创建一个新的字典列表。

我想我会使用来自 cython 的 c++,遍历这些 numpy 数组中的每一个,并在执行过程中构建一个映射向量。我似乎无法弄清楚如何在每次迭代中创建一个空地图。

我想做这样的事情:

def extract_data(words_seq, labels_seq, max_sentence_len):
    cdef int i
    cdef vector[map[string, vector[string]]] data
    cdef vector[string] new_entry

    data = []

    for i in range(len(words_seq)):
        cdef map[string, vector[string]] new_row_map = {}
        labels = labels_seq[i]
        words = words_seq[i]

        for j in range(max_sentence_len):
            label = labels_seq[i][j]
            word = words_seq[i][j]

            if label == 'junk':
                continue
            elif new_row_map.count(label) == 0:
                new_entry = [word]
                new_row_map[label] = new_entry
            else:
                new_row_map[label].push_back(word)
        data.push_back(new_row_map)

    return data

但我收到错误 cdef statement not allowed here。它也不喜欢我使用 dict 文字来声明一个空地图。

【问题讨论】:

    标签: python c++ cython


    【解决方案1】:

    cdef 必须在函数范围级别使用
    我的意思是在循环之外

    【讨论】:

    • 我该如何做到这一点并在每次迭代中创建一个新地图?如果我在循环外声明new_entry,我最终只会在每次迭代中附加同一个映射,其中包含新条目。
    【解决方案2】:

    事实证明我几乎是对的。地图的副本在每次迭代时附加到向量,而不是简单地指向地图的指针。因此,如果您在循环之外声明地图,然后在每次迭代时清除它,它似乎可以工作。

    def extract_data(words_seq, labels_seq, max_sentence_len):
        cdef int i, j
        cdef vector[map[string, vector[string]]] data
        cdef vector[string] new_entry
        cdef map[string, vector[string]] new_row_map
        cdef str label, word
    
        data = []
    
        for i in range(len(words_seq)):
    
            for j in range(max_sentence_len):
                label = labels_seq[i][j]
                word = words_seq[i][j]
    
                if label == 'junk':
                    continue
                elif new_row_map.count(label) == 0:
                    new_entry = [word]
                    new_row_map[label] = new_entry
                else:
                    new_row_map[label].push_back(word)
            data.push_back(new_row_map)
            new_row_map.clear()
    
        return data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 2012-03-31
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多