0

我有两个字典列表,一个是项目标识符列表,另一个是已完成项目标识符的列表。我希望根据已完成列表中的存在向项目标识符列表中添加一个键。

当前代码

>>> projects = [{'id': 1}, {'id': 2}, {'id': 3}]
>>> completes = [{'id': 1}, {'id': 2}]
>>> for complete in completes:
...     for project in projects:
...         if project["id"] == complete["id"]:
...             project["complete"] = 1
...         else:
...             project["complete"] = 0
...
>>> print projects
[{'id': 1, 'complete': 0}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]

预期产出

[{'id': 1, 'complete': 1}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]

项目被标记为完成后,如何跳出嵌套循环?我应该考虑另一种方法而不是使用嵌套循环吗?

4

3 回答 3

3

编辑 - 已修复(感谢@sotapme)

为什么不这样:

cids = [c['id'] for c in completes]
for project in projects:
    project["complete"] = project["id"] in cids

这将设置project["complete"]Trueor False,我建议这样做更好。如果你真的需要1and 0,那么:

    project["complete"] = int(project["id"] in cids)
于 2013-02-07T19:29:29.873 回答
1

如果将它们存储为由 id 键入的 dicts 而不是 dicts 数组,它会变得容易得多(在我看来):

projects = [{'id': 1}, {'id': 2}, {'id': 3}]
completes = [{'id': 1}, {'id': 2}]

projects_dict = {}
for p in projects:
    projects_dict[p['id']] = p

completes_dict = {}
for c in completes:
    completes_dict[c['id']] = c

for k in projects_dict.keys():
    projects_dict[k]['complete'] = int(k in completes_dict)

当然,不要循环完成,只需在创建“完成”数组的任何地方添加“完成”键。

于 2013-02-07T19:37:39.993 回答
1

我无法发表评论,但 jimhark 说的是好的,除了我认为你需要说类似的话

for project in projects:
    project['complete'] = project['id'] in (complete['id'] for complete in completes)

编辑:他已经改变了他的答案是正确的

于 2013-02-07T19:39:23.270 回答