【问题标题】:How to multiply the list values within a dictionary data type, while preserving the dictionary structure?如何将字典数据类型中的列表值相乘,同时保留字典结构?
【发布时间】:2016-11-30 03:15:33
【问题描述】:

在以下dict(类,列表)中:

defaultdict(<class 'list'>, {2480: ['0.25', '0.1', '0.083'], 2651: ['0.43', '0.11', '0.23']})
defaultdict(<class 'list'>, {2480: ['0.15', '0.15', '0.6'], 2651: ['0.26', '0.083', '0.23']})

我试过了:

for key, val in data.values():
    print(key, reduce(mul, (float(f) for f in val), 1))

这给了我错误:

for key, val in data.values(): AttributeError: 'str' object has no attribute 'values

也试过了,

for k1 in data.items():
    print(k1)

打印出来:

(2480, ['0.25', '0.1', '0.083']) (2651, ['0.43', '0.11', '0.23'])

但我无法使用 reduce(mul() 函数将浮点值相乘。

我想将浮点值相乘但保留类,保留列表值。

我希望输出是:

defaultdict(<class 'list'>, {2480: ['0.002075'], 2651: ['0.010879']})
defaultdict(<class 'list'>, {2480: ['0.0135'], 2651: ['0.0049634']})

但是,defaultdict(&lt;class 'list' 保留在这里只是为了显示数据结构。

谢谢,

【问题讨论】:

    标签: list python-3.x dictionary key-value-store multiplication


    【解决方案1】:

    你可以先定义一个multiply函数:

    >>> def multiply(*args):
    ...     res = args[0]
    ...     for arg in args[1:]:
    ...         res *= arg
    ...     return res
    

    如果你只有两个字典:

    d1_product = {key: multiply(*map(float, values)) for key, values in d1.items()}
    d2_product = {key: multiply(*map(float, values)) for key, values in d2.items()}
    

    虽然,如果你有两个以上的字典,你可能想尝试这样的事情(你必须稍微修改一下以跟踪单个字典,但是......也许可以尝试使用 enumerate,比如所以呢?

    res = {}
    for i, d in enumerate([d1, d2]):
        for key in d:
            values = map(float, d[key])
            product = multiply(*values)
            res[str(key) + str(i)] = product
    

    结果如下:

    >>> res
    {'24801': 0.0135, '26511': 0.004963400000000001, '24800': 0.002075, '26510': 0.010879000000000002}
    

    【讨论】:

      猜你喜欢
      • 2013-03-30
      • 2023-03-05
      • 2020-01-12
      • 1970-01-01
      • 2021-06-15
      • 2016-12-07
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      相关资源
      最近更新 更多