【问题标题】:Python: Convert 2d list to dictionary with indexes as valuesPython:将二维列表转换为以索引为值的字典
【发布时间】:2021-05-29 15:31:56
【问题描述】:

我有一个包含任意字符串的二维列表,如下所示:

    lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]

我想用这个创建一个字典:

    {'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}

我该怎么做? This answer 回答非重复值的一维列表,但是,我有一个二维列表,值可以重复。有通用的方法吗?

【问题讨论】:

    标签: python-3.x list


    【解决方案1】:

    也许你可以使用两个 for 循环:

    lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
    d = {}
    overall_idx = 0
    for sub_lst in lst:
        for word in sub_lst:
            if word not in d:
                d[word] = overall_idx
                # Increment overall_idx below if you want to only increment if word is not previously seen
                # overall_idx += 1
            overall_idx += 1
    print(d)
    

    输出:

    {'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
    

    【讨论】:

      【解决方案2】:

      您可以首先使用“双重”列表推导将列表列表转换为列表。

      接下来,使用字典推导去除所有重复项,我们可以使用set,但会丢失顺序。

      最后使用另一个字典推导得到想要的结果。

      lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
      
      # flatten list of lists to a list
      flat_list = [item for sublist in lst for item in sublist]
      
      # remove duplicates
      ordered_set = {x:0 for x in flat_list}.keys()
      
      # create required output
      the_dictionary = {v:i for i, v in enumerate(ordered_set)}
      
      print(the_dictionary)
      
      """ OUTPUT
      {'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
      """
      

      【讨论】:

        【解决方案3】:

        还有集合和迭代工具:

        import itertools
        from collections import OrderedDict
        
        lstdict={}
        lst = [['a', 'xyz' , 'tps'], ['rtr' , 'xyz']]
        lstkeys = list(OrderedDict(zip(itertools.chain(*lst), itertools.repeat(None))))
        lstdict = {lstkeys[i]: i for i in range(0, len(lstkeys))}
        lstdict
        

        输出:

        {'a': 0, 'xyz': 1, 'tps': 2, 'rtr': 3}
        

        【讨论】:

          猜你喜欢
          • 2019-09-17
          • 1970-01-01
          • 2016-07-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-17
          • 2022-10-06
          相关资源
          最近更新 更多