【问题标题】:Recommended method for grouping sqlite.Row rows分组 sqlite.Row 行的推荐方法
【发布时间】:2019-08-14 12:02:58
【问题描述】:

给定以下列表(来自 sqlite 查询):

[('job1', 'location1', 10), 
('job1', 'location2', 10),
('job2', 'location1', 5),
('job3', 'location1', 10),
('job3', 'location3', 10)]

我想在我的 tpl 模板中呈现以下内容:

job1
location1: 10
location2: 10

job2
location1: 5

job3
location1: 10
location3: 10

我或许可以用 setdefault 来完成这项工作

d = {}

for job in jobs:
    d.setdefault(job[0], {}).update({job[1]: job[2]})

但我想知道这样做的标准或最佳实践方式是什么?

干杯,

【问题讨论】:

    标签: python sqlite bottle


    【解决方案1】:

    以下是我如何让您的代码更 Pythonic:

    from collections import defaultdict
    
    d = defaultdict(dict)
    
    for (job_id, location, value) in jobs:
        d[job_id][location] = value
    
    # if you need an actual dict at the end (and not a defaultdict),
    # use d = dict(d)
    

    我改变了什么:

    1. 使用defaultdict
    2. 使用元组解包来提高可读性。

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 2019-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      相关资源
      最近更新 更多