检查一个赋值是否改变了目标对象的最惯用的方法

2024-06-07 21:22:28 发布

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

我需要比较两个dict并使它们相等(分配a->;b)。我还需要知道是否有任何值发生了变化,如果是这样,我需要运行一个计算开销很大的函数。我想出了一些有效的代码,但它看起来一点都不像python。你知道吗

有没有一种更像Python的方法??你知道吗

   def sync_data(activity_update_response, existing_quote):
        data_changed = False
        if activity_update_response["source"]["firstName"] != existing_quote["origin"]["applicant"]["firstName"]:
            activity_update_response["source"]["firstName"] = existing_quote["origin"]["applicant"]["firstName"]
            data_changed = True

        if activity_update_response["source"]["lastName"] != existing_quote["origin"]["applicant"]["surname"]:
            activity_update_response["source"]["lastName"] = existing_quote["origin"]["applicant"]["surname"]
            data_changed = True

        # ( ... )
        # repeat for 4 more fields

        if data_changed:
            # this is slow
            recalculate_hashes(activity_update_response)

Tags: truesourcedataifresponseupdateoriginactivity
3条回答

我认为将变量存储在data_changed中是一种很好的方法。我认为这看起来不像Python的原因是你在重复你自己(不是干巴巴的)。你知道吗

我还没有测试过这个,但是你可以试着沿着这条线做更多的事情。你知道吗

def sync_data(activity_update_response, existing_quote):
    data_changed = False

    origin = existing_quote["origin"]["applicant"]
    source = activity_update_response["source"]

    for field in ("firstName", "lastName",):  # Extend with 4 more fields
        data_changed = data_changed or origin[field] != source[field]
        source[field] = origin[field]

    if data_changed:
        # this is slow
        recalculate_hashes(activity_update_response)

收集要更新的密钥,然后更新dict并重新计算哈希值。python3.8中新的赋值表达式操作符很方便。你知道吗

def sync_data(activity_update_response, existing_quote):
    # XXX Pick good names
    a = activity_update_response["source"]
    e = existing_quote["origin"]["applicant"]
    fields = ["lastName", "firstName", ...]

    #if (keys_to_update := [x for x in fields if a[x] != e[x]]):
    keys_to_update = [x for x in fields if a[x] != e[x]]
    if keys_to_update:
        recalculate_hashes(activity_update_response)
        for key in keys_to_update:
            a[key] = e[key]

为了使代码更具可读性,我建议:

def sync_data(activity_update_response, existing_quote):
    Fields = ("firstName", "lastName", )# add 4 more fields
    for field in Fields:
        if activity_update_response["source"][field] != existing_quote["origin"]["applicant"][field]
            activity_update_response["source"].update({f: existing_quote["origin"]["applicant"][f] for f in Fields})
            recalculate_hashes(activity_update_response)
            break

我看不出还有更多的重构要做,因为这基本上就是您正在尝试做的。你知道吗

相关问题 更多 >

    热门问题