比较一个字典列表,每个字典都有逻辑和动作

2024-09-28 18:50:56 发布

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

这里有很多相关的问题,但没有一个我可以破译,以满足我的标准。所以我要做的是检查一个活动计划是否在计划的\u站点中,如果它是离开它,如果它不是,那么将它添加到计划的\u站点并将仪表板设置为false

样本数据:

>>> scheduled_sites
[{'id': 128, 'scheduled_dashboard': True}, {'id': 61, 'scheduled_dashboard': True}]
>>> active_schedules
[{'id': 1, 'scheduled_dashboard': True},{'id': 61, 'scheduled_dashboard': True}]

预期结果:

[{'id': 128, 'scheduled_dashboard': True}, {'id': 61, 'scheduled_dashboard': True}, {'id': 1, 'scheduled_dashboard': False}]

我觉得我与下面的接近,但得到错误或空白。。。你知道吗

>>> if any(a["id"] == s["id"] for s in scheduled_sites for a in active_schedules):
...     s
...
>>> if any(a["id"] == s["id"] for s in scheduled_sites for a in active_schedules):
...     a
...
Traceback (most recent call last):
  File "<console>", line 2, in <module>
NameError: name 'a' is not defined
>>>

Tags: inidtruefor标准if站点any
3条回答

这个怎么样?你知道吗

for active in active_schedules:
    if not any(active == scheduled for scheduled in scheduled_sites):
        new_site = {
            'id': active['id'],
            'scheduled_dashboard': False,
        }
        scheduled_sites.append(new_site)

理解语法只将变量保留在调用any的范围内。为了保留变量,您需要显式地定义循环,或者在理解范围内存储结果。你知道吗

for a in active_schedules:
     for s in scheduled_sites:
         if a['id'] == s['id']:
             print("a: {}, a: {}".format(a, s))

输出:

a: {'id': 61, 'scheduled_dashboard': True}, a: {'id': 61, 'scheduled_dashboard': True}

sa仅在any(...)的生成器理解中定义-您不能从外部访问。你知道吗

改用普通循环/集合/dict:

import copy

scheduled_sites  = [{'id': 128, 'scheduled_dashboard': True}, 
                    {'id':  61, 'scheduled_dashboard': True}]
active_schedules = [{'id':   1, 'scheduled_dashboard': True},
                    {'id':  61, 'scheduled_dashboard': True}]


# get missing keys
scheduled = set( (k["id"] for k in scheduled_sites) )
active = set( (k["id"] for k in active_schedules) )

# for lots of schedules it is cheaper to only iterate those that are missing
not_scheduled = active-scheduled

for not_in in not_scheduled:
    for d in active_schedules:
        if d["id"] == not_in:
            # copy the dict you need to decouple this reference from the other one
            scheduled_sites.append(copy.deepcopy(d))
            scheduled_sites[-1]["scheduled_dashboard"] = False

print(scheduled_sites)

输出:

[{'id': 128, 'scheduled_dashboard': True}, 
 {'id': 61, 'scheduled_dashboard': True},
 {'id': 1, 'scheduled_dashboard': False}]

相关问题 更多 >