建议的分组方法sqlite.行排

2024-09-24 06:24:00 发布

您现在位置:Python中文网/ 问答频道 /正文

给定以下列表(来自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]})

但我想知道做这件事的标准或最佳做法是什么?你知道吗

干杯


Tags: in模板列表forsqlitejobsjobtpl
1条回答
网友
1楼 · 发布于 2024-09-24 06:24:00

下面是我如何让你的代码更像Python:

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. 使用元组解包以增加可读性。你知道吗

相关问题 更多 >