【问题标题】:How to flatten the value (list of lists of tuples) of a key in Python dictionary?如何展平Python字典中键的值(元组列表列表)?
【发布时间】:2020-06-22 13:09:25
【问题描述】:

我在 python 中有一个字典,看起来像这样:

   {(-1, 1): (0, 1),
   (0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
   (0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
   (0, 2): (0, 1)} 

我不希望它有所有这些额外的括号和括号。 这是我用来创建这个字典的代码:

      if condition1==True:
        if condition2==True:

           if (x,y) in adjList_dict:  ##if the (x,y) tuple key is already in the dict

               ##add tuple neighbours[i] to existing list of tuples 
               adjList_dict[(x,y)]=[(adjList_dict[(x,y)],neighbours[i])] 

                    else:
                        adjList_dict.update( {(x,y) : neighbours[i]} )

我只是想创建一个字典,其中键是元组,每个键的值是元组列表。

例如我想要这个结果:(0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)]

我可以展平输出还是应该在创建字典时更改某些内容?

【问题讨论】:

    标签: python dictionary tuples nested-lists flatten


    【解决方案1】:

    您可以使用递归,然后测试实例是否是一个简单的元组,其中包含 int 值,例如:

    sample = {(-1, 1): (0, 1),
       (0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
       (0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
       (0, 2): (0, 1)}
    
    
    def flatten(data, output):
        if isinstance(data, tuple) and isinstance(data[0], int):
            output.append(data)
        else:
            for e in data:
                flatten(e, output)
    
    
    output = {}
    for key, values in sample.items():
        flatten_values = []
        flatten(values, flatten_values)
        output[key] = flatten_values
    
    print(output)
    >>> {(-1, 1): [(0, 1)], (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)], (0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)], (0, 2): [(0, 1)]}
    
    

    【讨论】:

      【解决方案2】:

      您可以使用具有字典理解的递归方法:

      d = {(-1, 1): (0, 1),
         (0, 0): [([([(1, 0), (0, 1)], (0, 1))], (1, 0))],
         (0, 1): [([([((-1, 1), (0, 2))], (1, 1))], (0, 0))],
         (0, 2): (0, 1)}
      
      
      
      def flatten(e):
          if isinstance(e[0], int):
              yield e
          else:    
              for i in e:
                  yield from flatten(i)
      
      {k: list(flatten(v)) for k, v in d.items()}
      

      输出:

      {(-1, 1): [(0, 1)],
       (0, 0): [(1, 0), (0, 1), (0, 1), (1, 0)],
       (0, 1): [(-1, 1), (0, 2), (1, 1), (0, 0)],
       (0, 2): [(0, 1)]}
      

      【讨论】:

        猜你喜欢
        • 2021-09-07
        • 2018-07-19
        • 2019-11-04
        • 2020-03-27
        • 1970-01-01
        • 1970-01-01
        • 2015-05-02
        • 2011-09-05
        • 2016-06-26
        相关资源
        最近更新 更多