gpt4 book ai didi

python - 通过乘法将两个 python 字典与元组组合起来 - Python 3.x

转载 作者:行者123 更新时间:2023-12-01 07:12:09 25 4
gpt4 key购买 nike

我有两个命令:

d2 = {'dog': 1.0, 'bird': 0.0, 'egret': 2.0, 'aardvark': 1.0, 'cat': 3.0, 'fish': 2.0}

d1 = {1: [('dog', 3), ('bird', 1)], 2: [('egret', 1), ('aardvark', 1), ('cat', 1), ('bird', 2)], 3: [('dog', 1), ('aardvark', 5), ('fish', 3), ('bird', 1)], 4: [('dog', 1), ('aardvark', 2), ('fish', 3), ('bird', 1)], 5: [('egret', 2), ('bird', 1)], 6: [('bird', 1)], 7: [('dog', 5), ('bird', 6)], 8: [('aardvark', 1), ('bird', 8)]}

我需要完成的是,对于每个元组,在d1中查找元组的第一个值,并将第二个值乘以d1中的值。所以 d2 最终应该看起来像:

d3 = {1: [('dog', 3), ('bird', 0)], 2: [('egret', 2), ('aardvark', 1), ('cat', 3), ('bird', 0)], 3: [('dog', 1), ('aardvark', 5), ('fish', 6), ('bird', 0)], 4: [('dog', 1), ('aardvark', 2), ('fish', 6), ('bird', 0)], 5: [('egret', 4), ('bird', 0)], 6: [('bird', 0)], 7: [('dog', 5), ('bird', 0)], 8: [('aardvark', 1), ('bird', 0)]}

我试图实现这一目标:

for key, val in d1.items():
currVal = val[0][0]
num = [val for k, v in d2.items() if key == currVal]
multiplier = num[0]
val[0][1] = val[0][1] * multiplier

但是我收到 IndexError: list index out of range 我认为这是因为我错误地访问了字典。

最佳答案

您可以使用字典理解:

d2 = {'dog': 1.0, 'bird': 0.0, 'egret': 2.0, 'aardvark': 1.0, 'cat': 3.0, 'fish': 2.0}
d1 = {1: [('dog', 3), ('bird', 1)], 2: [('egret', 1), ('aardvark', 1), ('cat', 1), ('bird', 2)], 3: [('dog', 1), ('aardvark', 5), ('fish', 3), ('bird', 1)], 4: [('dog', 1), ('aardvark', 2), ('fish', 3), ('bird', 1)], 5: [('egret', 2), ('bird', 1)], 6: [('bird', 1)], 7: [('dog', 5), ('bird', 6)], 8: [('aardvark', 1), ('bird', 8)]}
new_d = {a:[(c, int(d2[c]*d)) for c, d in b] for a, b in d1.items()}

输出:

{1: [('dog', 3), ('bird', 0)], 2: [('egret', 2), ('aardvark', 1), ('cat', 3), ('bird', 0)], 3: [('dog', 1), ('aardvark', 5), ('fish', 6), ('bird', 0)], 4: [('dog', 1), ('aardvark', 2), ('fish', 6), ('bird', 0)], 5: [('egret', 4), ('bird', 0)], 6: [('bird', 0)], 7: [('dog', 5), ('bird', 0)], 8: [('aardvark', 1), ('bird', 0)]}

关于python - 通过乘法将两个 python 字典与元组组合起来 - Python 3.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58150800/

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