1

背景

我想创建字典,每个单词都有一个唯一的 id 用于词嵌入目的。数据集如下所示:

s_lists = [['I', 'want', 'to', 'go', 'to', 'the', 'park'],
           ['I', 'want', 'to', 'quit', 'the', 'team']]

以下功能正在构建字典

def build_dict(input_list, start=2):
    """
    build dictionary
    start with 2,1 for unknow word,0 for zero padding

    :param input_list:
    :param start:
    :return: custom dictionary
    """

    whole_set = set()
    for current_sub_list in input_list:
         # remove duplicate elements
        current_set = set(current_sub_list)
        # add new element into whole set
        whole_set = whole_set | current_set
    return {ni: indi + start for indi, ni in enumerate(whole_set)}

它工作并输出

{'I': 7,'go': 2,'park': 4,'quit': 8, 'team': 6,'the': 5,'to': 9,'want': 3}

问题

当我将它用于大型数据集(大约 50w 个字符串)时,它将花费大约30 秒(ENV mbpr15-i7)。它太慢了,我想寻找一个解决方案来提高性能,但我现在不知道。

4

3 回答 3

1

试试下面的代码itertools.chain。在我的测试用例中,它的工作速度大约是 x4:

from itertools import chain

start = 2
{it: n + start for n, it in enumerate(set(chain(*s_lists)))}
于 2018-06-20T06:42:04.973 回答
1

您可以使用chainand countfrom itertools

>>> from itertools import chain,count
>>> 
>>> dict(zip(set(chain(*s_lists)), count(2)))
{'team': 2, 'park': 3, 'want': 4, 'I': 5, 'the': 6, 'quit': 7, 'to': 8, 'go': 9}
>>> 
于 2018-06-20T06:54:40.050 回答
0

试试这样的,

flatern_s_lists = [item for sub_item in s_lists for item in sub_item]
result = {j:i+2 for i,j in enumerate(set(flatern_s_lists))}

在执行速度的情况下,制作一个列表来奉承这是最好的选择。

结果:

{'quit': 2, 'I': 3, 'park': 4, 'to': 5, 'want': 6, 'team': 7, 'go': 8, 'the': 9}
于 2018-06-20T07:00:00.863 回答