代码之家  ›  专栏  ›  技术社区  ›  Leoli

如何更快地从字符串列表生成自定义词典

  •  1
  • Leoli  · 技术社区  · 8 年前

    背景

    我想创建一个字典,每个单词都有一个用于嵌入单词的唯一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)。它是 太慢了 我想寻找一个提高性能的解决方案,但目前我还不知道。

    3 回复  |  直到 8 年前
        1
  •  1
  •   koPytok    8 年前

    尝试以下代码 itertools.chain

    from itertools import chain
    
    start = 2
    {it: n + start for n, it in enumerate(set(chain(*s_lists)))}
    
        2
  •  1
  •   Sunitha    8 年前

    你可以用 chain count 来自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}
    >>> 
    
        3
  •  0
  •   Rahul K P no11    8 年前

    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}