我有一个字典列表,需要使用另一个字典列表中的信息进行更新。我当前的解决方案(如下)的工作方式是从第一个列表中取出每个词典,然后将其与第二个列表中的每个词典进行比较。它可以工作,但是有没有更快,更优雅的方法来达到相同的结果呢?a = [ { "id": 1, "score":200 }, { "id": 2, "score":300 }, { "id":3, "score":400 } ]b = [ { "id": 1, "newscore":500 }, { "id": 2, "newscore":600 } ]# update a with data from bfor item in a: for replacement in b: if item["id"]==replacement["id"]: item.update({"score": replacement["newscore"]})
3 回答
有只小跳蛙
TA贡献1824条经验 获得超8个赞
通过id使用第一个数组创建索引的字典。使用循环遍历第二个数组id。
for replacement in b:
v = lookup.get(replacement['id'], None)
if v is not None:
v['score'] = replacement['newscore']
这将O(n^2)问题转化为O(n)问题。
梵蒂冈之花
TA贡献1900条经验 获得超5个赞
与其进行len(a)* len(b)循环,不如将b加工成更易于使用的东西:
In [48]: replace = {d["id"]: {"score": d["newscore"]} for d in b}
In [49]: new_a = [{**d, **replace.get(d['id'], {})} for d in a]
In [50]: new_a
Out[50]: [{'id': 1, 'score': 500}, {'id': 2, 'score': 600}, {'id': 3, 'score': 400}]
请注意,该{**somedict}语法要求使用现代版本的Python(> = 3.5)。
扬帆大鱼
TA贡献1799条经验 获得超9个赞
清单理解:
[i.update({"score": x["newscore"]}) for x in b for i in a if i['id']==x['id']] print(a)
输出:
[{'id': 1, 'score': 500}, {'id': 2, 'score': 600}, {'id': 3, 'score': 400}]
定时:
%timeit [i.update({"score": x["newscore"]}) for x in b for i in a if i['id']==x['id']]
输出:
100000 loops, best of 3: 3.9 µs per loop
添加回答
举报
0/150
提交
取消