代码之家  ›  专栏  ›  技术社区  ›  culebrón

创建或附加到字典中的列表-可以缩短吗?

  •  43
  • culebrón  · 技术社区  · 14 年前

    使用itertools和set可以缩短Python代码并使其可读吗?

    result = {}
    for widget_type, app in widgets:
        if widget_type not in result:
            result[widget_type] = []
        result[widget_type].append(app)
    

    我只能这样想:

    widget_types = zip(*widgets)[0]
    dict([k, [v for w, v in widgets if w == k]) for k in set(widget_types)])
    
    3 回复  |  直到 14 年前
        1
  •  55
  •   Mark Byers    14 年前

    你可以用 defaultdict(list) .

    from collections import defaultdict
    
    result = defaultdict(list)
    for widget_type, app in widgets:
        result[widget_type].append(app)
    
        2
  •  94
  •   Daniel Roseman    14 年前

    替代品 defaultdict setdefault 标准词典的方法:

     result = {}
     for widget_type, app in widgets:
         result.setdefault(widget_type, []).append(app)
    

        3
  •  4
  •   user1139002    12 年前

    可能有点慢但有效

    result = {}
    for widget_type, app in widgets:
        result[widget_type] = result.get(widget_type, []) + [app]