在 Python 中填充二维数组的有效方法
Efficient way to fill 2d array in Python
我有 3 个数组:数组 "words" 对 ["id": "word"] 的长度为 5000000,唯一 ID 的数组 "ids" 的长度为 13000 和长度为 500000 的独特单词(字典)数组 "dict"。这是我的代码:
matrix = sparse.lil_matrix((len(ids), len(dict)))
for i in words:
matrix[id.index(i['id']), dict.index(i['word'])] += 1.0
但是速度太慢了(搞了15个小时还没矩阵)。有什么想法可以优化我的代码吗?
首先不要将数组命名为 dict
,这会造成混淆并隐藏内置类型 dict
。
这里的问题是你在二次时间做所有事情,所以首先将数组 dict
和 id
转换为字典,其中每个 word
或 id
指向它的索引。
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
我有 3 个数组:数组 "words" 对 ["id": "word"] 的长度为 5000000,唯一 ID 的数组 "ids" 的长度为 13000 和长度为 500000 的独特单词(字典)数组 "dict"。这是我的代码:
matrix = sparse.lil_matrix((len(ids), len(dict)))
for i in words:
matrix[id.index(i['id']), dict.index(i['word'])] += 1.0
但是速度太慢了(搞了15个小时还没矩阵)。有什么想法可以优化我的代码吗?
首先不要将数组命名为 dict
,这会造成混淆并隐藏内置类型 dict
。
这里的问题是你在二次时间做所有事情,所以首先将数组 dict
和 id
转换为字典,其中每个 word
或 id
指向它的索引。
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