gpt4 book ai didi

python - 如何更自然地获取更新列表而不使用标志

转载 作者:太空宇宙 更新时间:2023-11-04 00:07:13 24 4
gpt4 key购买 nike

我有两个列表是

old_list = [{"tag": "apple","value":4}, {"tag": "orange","value":5}]
new_list = [{"tag": "apple","value":1}, {"tag": "orange","value":2}, {"tag": "grape","value":3}]

我想要一个 new_list,如果 new_list 的 item['tag'] 等于 old_list 的 item['tag'] new_list['value'] 等于 old_list['value'],如果 new_list 有新项,
然后 new_list['value'] 初始化 0.

结果:

new_list = [{"tag": "apple","value":4}, {"tag": "orange","value":5}, {"tag": "grape","value":0}]

这是我的工具:

old_list = [{"tag": "apple","value":4}, {"tag": "orange","value":5}]
new_list = [{"tag": "apple","value":1}, {"tag": "orange","value":2}, {"tag": "grape","value":3}]
update_list = []
for new in new_list:
flag_new_item = True
for old in old_list:
if new["tag"] == old['tag']:
new["value"] = old['value']
flag_new_item = False
break
if flag_new_item:
new['value'] = 0
print(new_list)

因为我使用 2'times 迭代器来实现这个问题,我认为它太慢并且不是 python 风格,而且我引入了看起来不太好的新标志。有没有更直接、方便、高效的实现方式

最佳答案

您可以从 old_list 创建一个 tagvalue 字典并适本地更新 new_list 项目:

old_list = [{"tag": "apple","value":4}, {"tag": "orange","value":5}]
new_list = [{"tag": "apple","value":1}, {"tag": "orange","value":2}, {"tag": "grape","value":3}]

# create a dictionary from old_list
old_tags = {i['tag']: i['value'] for i in old_list}

# update new_list with old_list values if present
for item in new_list:
item['value'] = old_tags.get(item['tag'], 0)

print(new_list)

输出

[{'tag': 'apple', 'value': 4}, {'tag': 'orange', 'value': 5}, {'tag': 'grape', 'value': 0}]

关于python - 如何更自然地获取更新列表而不使用标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53716879/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com