【问题标题】:How to group values in list of lists and convert to list of dictionaries如何对列表列表中的值进行分组并转换为字典列表
【发布时间】:2020-05-17 20:22:31
【问题描述】:

我有一个包含行号和列号的列表,如下所示:

list_of_lists = [[100, 300],
                 [100, 301],
                 [100, 302],
                 [101, 200],
                 [101, 201],
                 [102, 210]]

其中行号是每个子列表的第一个值;第二个值的列号。

我需要以某种方式将其转换为字典列表,如下所示:

dict = [{'row': 100, 'columns': [300, 301, 302]},
        {'row': 101, 'columns': [200, 201]},
        {'row': 102, 'columns': 210}]

关于如何做到这一点的任何建议?

【问题讨论】:

  • 效率低下,然后改进。
  • 到目前为止您尝试过什么?提示:您可能希望所有值都具有相同的结构,因此在最后一项中使用单个值的列表,而不仅仅是不在列表中的值
  • 我按照@Datanovice 的建议尝试了 defaultdict 并且成功了。我还使用 numpy.unique 仅获取唯一的列值。像这样: [{'row': k, 'column': np.unique(v)} for k,v in value_dict.items()]

标签: python list dictionary type-conversion grouping


【解决方案1】:

使用集合库中的defaultdict

首先我们将您的项目分组,然后使用列表组合创建您的嵌套字典列表。

from collections import defaultdict

group_dict = defaultdict(list)
for item in list_of_lists:
    group_dict[item[0]].append(item[1])

final = [{'row' : k, 'column' : v} for k,v in group_dict.items()]

print(final)
[{'row': 100, 'column': [300, 301, 302]},
 {'row': 101, 'column': [200, 201]},
 {'row': 102, 'column': [210]}]

【讨论】:

    【解决方案2】:

    这是一个真正快速的方法,但它并不漂亮。这里有两种输出数据的方法(第一种不是您的首选输出,但它可能使您的数据在将来更容易访问):

    list_of_lists = [[100, 300],
                     [100, 301],
                     [100, 302],
                     [101, 200],
                     [101, 201],
                     [102, 210]]
    
    # create a dict with empty lists as keys
    pivot = {i[0]: [] for i in list_of_lists}
    for i in list_of_lists:
        # append the value of the first item key to the second item
        pivot[i[0]].append(i[1])
    
    # split dict items into their own dicts with row and column keys
    pivot_with_keys = [{'row': k, 'columns': v}
                       for k, v in pivot.items()]
    
    print(f'rows as keys: {pivot}')
    print(f'text as keys: {pivot_with_keys}')
    

    输出

    rows as keys: {100: [300, 301, 302], 101: [200, 201], 102: [210]}
    text as keys: [{'row': 100, 'columns': [300, 301, 302]}, {'row': 101, 'columns': [200, 201]}, {'row': 102, 'columns': [210]}]
    

    【讨论】:

      【解决方案3】:

      另一种方法是使用来自 itertools 的 groupbyislicechain:根据每个列表中的第一个条目对值进行分组,获取组并通过 for 循环附加到字典中:

      from itertools import groupby, islice, chain
      from operator import itemgetter    
      
      #note that for groupby, the data has to be sorted
      #easily achieved using the sorted method
      #supplied data is already sorted, so i'll skip
      
      m = groupby(list_of_lists, key = itemgetter(0))
      d = []
      for k,v in m: 
          #zip the groupings and keep only the [-1] entry for each
          res = islice(zip(*v),1,None)
          #merge into one
          res = list(chain.from_iterable(res))
          d.append({'row':k, 'columns':res})
      
      print(d)
      
      [{'row': 100, 'columns': [300, 301, 302]},
       {'row': 101, 'columns': [200, 201]},
       {'row': 102, 'columns': [210]}]
      

      注意:这是一种替代方法 - defaultdict 方法更快(大约 2X)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-25
        相关资源
        最近更新 更多