gpt4 book ai didi

python - 字典中的元组

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

我有两个列表。每个列表都按颜色和州显示了一个人购买的商品。我想找到两者之间的区别。两个名单中的人数并不相同。

list1 = [{'Jeff':{'Red':(0.4, 'NY'), 'Green':(0.6, 'NJ'), 'Blue': (0.3, 'NJ')}}]
list2 = [{'Steve':{'Red':(0.2, 'NY'), 'Green':(0.8, 'NJ'), 'Black':(0.7, 'CT') }}]

list1[0]list2[0] 之间的差异是 1.4。按颜色计算:红(0.2)+绿(0.2)+蓝(0.3)+黑(0.7)。按州划分,差异为 NY (0.2)、NJ(0.5 = 0.2 + 0.3) 和 CT(0.7)。

我一直在尝试以下方法:

def diff(first, second):

diff = 0
templist = []

for color, purchase in first.items():
other = second.get(color)
if other is not None:
diff += abs(purchase[0] - second[color][0])
templist.append((first[color][1], diff))
else:
diff += purchase[0]
templist.append((first[color][1], diff))


for color, purchase in second.items():
other = first.get(color)
if other is None:
diff += purchase[0]
templist.append((second[color][1], diff))

return diff, templist

如何按 list1 中每个人的状态在下面的列表中获取所需的输出?谢谢。

  Jeff  1.4  [NY, 0.2]  [NJ, 0.5]  [CT, 0.7]  

最佳答案

templist 中的 diff 函数有错误。您应该附加当前的色差而不是累积的差异。然后,您应该将同一城市对应的所有值相加。

应该是:

def diff(first, second):
diff = 0
templist = []

for color, purchase in first.items():
other = second.get(color)
if other is not None:
color_diff = abs(purchase[0] - second[color][0])
diff += color_diff
templist.append((first[color][1], color_diff))
else:
color_diff = purchase[0]
diff += color_diff
templist.append((first[color][1], color_diff))

for color, purchase in second.items():
other = first.get(color)
if other is None:
color_diff = purchase[0]
diff += color_diff
templist.append((second[color][1], color_diff))

# Sum templist
templist = [
(c, sum([v for c_in, v in templist if c_in == c]))
for c in set([i[0] for i in templist])
]

return diff, templist

关于python - 字典中的元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55092172/

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