【问题标题】:Adding values corresponding to one key in python dictionary在python字典中添加与一个键对应的值
【发布时间】:2014-03-19 01:42:18
【问题描述】:

我有一本字典:

d = {'0.766': [('8.0', '-58.47'), ('192.0', '-83.41')], '0.094': [('26.0', '112.01'), ('46.0', '110.19')], '0.313': [('14.0', '75.52'), ('48.0', '77.07')]}

我想在元组中添加相应的值,所以输出看起来像这样:

key, sum of 1st values in tuple, sum of 2nd values in tuple
0.766, 200.0, -141.88
0.094, 72.0, 222.20
...

有没有简单的方法来做到这一点?到目前为止,我找到了 sum(d.values()),但它并没有完全按照我的意愿去做......

干杯, 凯特

PS。现在我也想知道如何获得输出,例如:

key, sum of 1st values in tuple, DIFFERENCE of 2nd values in tuple
0.766, 200.0, 24.94
0.094, 72.0, 1.82
...

当我想执行两个不同的操作时...

谢谢!

【问题讨论】:

    标签: python dictionary tuples


    【解决方案1】:
    print [(k,) + tuple(sum(map(float, item)) for item in zip(*d[k])) for k in d]
    # [('0.766', 200.0, -141.88),
    #  ('0.313', 62.0, 152.58999999999997),
    #  ('0.094', 72.0, 222.2)]
    

    我们上面所说的称为列表推导。它实际上与此类似,但以一种有效的方式工作

    result = []
    for k in d:
        temp = tuple()
        for item in zip(*d[k]):
            temp += (sum(map(float, item)),)
        result.append((k,) + temp)
    print result
    

    要处理您在编辑问题中提到的情况,您可以执行以下操作

    result = []
    for k in d:
        temp = tuple()
        fir, sec = zip(*d[k])
        fir, sec = sum(map(float, fir)), reduce(lambda i,j: float(i)-float(j), sec)
        result.append((k,) + (fir, sec))
    print result
    

    【讨论】:

    • +1,但为了我的钱,列表理解是这里最简单的事情。 zip(*x)sum(map(float, item)) 位是聚合和函数式编程,与 IMO 列表理解一样难以理解。
    • 我现在想知道,如果我正在寻找键、元组中第一个值的总和、元组中第二个值的差异,我将如何更改代码?
    • @kate88 可以提供样品吗?
    【解决方案2】:

    我认为这个答案可能更直观一点。它不使用令我困惑的“*”:

    print "\n".join(
        [
            "%s, %s, %s" % 
            (
                i, 
                sum([float(j[0]) for j in d[i]]), 
                sum([float(j[1]) for j in d[i]]),
            ) 
            for i in d.keys()
        ]
    )
    

    您遇到的后续问题将需要实际编写循环,因为您不是简单地添加(或执行类似的累积操作)数字列表。相反,您是从第一个数字中减去第二个数字。由于顺序很重要,因此我上面显示的列表理解不起作用。

    【讨论】:

      猜你喜欢
      • 2019-02-08
      • 2018-05-27
      • 2020-06-10
      • 1970-01-01
      • 2012-05-09
      • 1970-01-01
      • 2016-10-29
      • 2012-07-08
      • 1970-01-01
      相关资源
      最近更新 更多