【问题标题】:Efficient way to fill 2d array in Python在 Python 中填充二维数组的有效方法
【发布时间】:2015-07-19 04:15:05
【问题描述】:

我有 3 个数组:长度为 5000000 的数组“单词”对 [“id”:“单词”],长度为 13000 的唯一 ID 数组“ids”和唯一单词的数组“dict”(字典)长度为 500000。这是我的代码:

matrix = sparse.lil_matrix((len(ids), len(dict)))
for i in words:
    matrix[id.index(i['id']), dict.index(i['word'])] += 1.0

但它工作得太慢(工作 15 小时后我还没有得到矩阵)。有什么想法可以优化我的代码吗?

【问题讨论】:

    标签: python performance optimization scipy sparse-matrix


    【解决方案1】:

    首先不要将你的数组命名为dict,它会让人困惑并且隐藏了内置类型dict

    这里的问题是您在二次时间中做所有事情,因此首先将您的数组dictid 转换为字典,其中每个wordid 都指向它的索引。

    matrix = sparse.lil_matrix((len(ids), len(dict)))
    dict_from_dict = {word: ind for ind, word in enumerate(dict)}
    dict_from_id = {id: ind for ind, id in enumerate(id)}
    for i in words:
        matrix[dict_from_id[i['id']], dict_from_dict[i['word']] += 1.0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2018-04-13
      • 2016-05-27
      • 2021-06-03
      • 1970-01-01
      相关资源
      最近更新 更多