gpt4 book ai didi

python - 有人可以解释这是如何通过字典循环的吗?

转载 作者:太空宇宙 更新时间:2023-11-04 04:16:12 26 4
gpt4 key购买 nike

我有两本词典,我想比较它们,看看两者有什么不同。我感到困惑的地方是 dict。这个有名字吗?

一切正常,我只是不太明白它为什么有效或它在做什么。

x = {"#04": 0, "#05": 0, "#07": 0, "#08": 1, "#09": 0, "#10": 0, "#11": 1, "#12": 1, "#14": 1, "#15": 1, "#17": 0, "#18": 1, "#19": 1, "#20": 1}

y = {"#04": 1, "#05": 0, "#07": 0, "#08": 1, "#09": 0, "#10": 0, "#11": 1, "#12": 1, "#14": 1, "#15": 0, "#17": 1, "#18": 1, "#19": 0, "#20": 1}

dict = {k: x[k] for k in x if y[k] != x[k]}

list = []

for k, v in dict.items()
if v==0:
difference = k + ' became ' + '0'
list.append(difference)
else:
difference = k + ' became ' + '1'
list.append(difference)

print(list)

它应该打印 ['#04 变成 0', '#15 变成 1', '#17 变成 0', '#19 变成 1'] 但我不明白dict 用于循环遍历 x 和 y 字典。

最佳答案

实现的过程是比较两个字典,假设它们具有相同的键(可能 y 可能有更多条目)。

为了快速进行这种比较,并方便下一个代码块,他们决定生成一个只包含具有不同值的键的字典。

为了生成这样的字典,他们使用了一种非常有效的“字典理解”。

现在,这个结构:

d = {k: x[k] for k in x if y[k] != x[k]}

可以重写为:

d = {}
for k,v in x: # for each key->value pairs in dictionary x
if y[k] != x[k]: # if the corresponding elements are different
d[k] = x[k] # store the key->value pair in the new dictionary

您可以将上面的 x[k] 替换为 v

关于python - 有人可以解释这是如何通过字典循环的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55368472/

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