python - 字典中的元组

标签 python pandas

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

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/

相关文章:

python - 从字典中删除重复的 Pandas 数据框

python - 将一个系列或数组限制在一个值范围内

Python:以逗号作为小数点分隔符加载数据

python - 将函数名称作为参数传递以定义通用函数

python - 类型错误 : bar() got multiple values for keyword argument 'height'

python - 将具有多个列表的文本文件读取到 pandas dataframe 中,列表中的元素之间存在空格和逗号

python - pandas:使用 to_excel 写入现有的 excel 文件 (xlsx)

python - 我可以在 Web 应用程序中使用 JetBrains MPS 吗?

python - 如何根据条件从数据框中删除行

Python Pandas 动态创建数据框