python - 给定二维列表和值库的所有值的加权平均值

标签 python python-3.x list loops

我有三个不同的列表:

a = [[7,5,8],[3,4]]

value = [9, 5, 7, 8, 3, 4, 10]
weight = [100.0, 65.0, 25.0, 25.0, 100.0, 65.0, 25.0]
capacity = [1000.0, 15.0, 700.0, 700.0, 1000.0, 15.0, 700.0]

我试图找到给定条目中所有值总和的权重和容量,例如在a[0]中:

weight_a[0] = (700*25 + 15*65 + 700*25) / (700 + 15 + 700)
capacity_a[0] = 700 + 15 + 700

weight_a[1] = (1000*100 + 15*65) / (1000 + 15)
capacity_a[1] = 1000 + 15

因此weight_a和capacity_a是a的每个列表中的条目的weighted_average和capacity之和。

值 7 的重量为 25,容量为 700:

7 is value[2] so capacity[2] = 700 and weight[2] = 25

weight_a方程为sum(值的权重*值的容量)/所有值的容量之和

capacity_a方程是所有值的容量之和

我一直在试图阐述这个问题,但似乎无法弄清楚。我正在尝试压缩(值、容量、重量),但我不确定如何访问给定的二维列表 a。

感谢任何帮助!

最佳答案

您可以将 map 与自定义函数结合使用,然后使用 zip 解压结果:

from operator import itemgetter, mul

def calculator(k):
    k_set = set(k)
    getter = itemgetter(*(idx for idx, i in enumerate(value) if i in k_set))
    weights, caps = map(getter, (weight, capacity))
    capsum = sum(caps)
    return sum(map(mul, weights, caps)) / capsum, capsum

weight_a, capacity_a = zip(*map(calculator, a))

print(weight_a, capacity_a)

(25.424028268551236, 99.48275862068965) (1415.0, 1015.0)

关于python - 给定二维列表和值库的所有值的加权平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53049840/

相关文章:

python - 如何从txt文件中删除特定行及其后面的n行?

python - 在单独的线程上关闭 wxPython 应用程序会遇到窗口警报

python - 通过 tcp/ip 连接以脚本语言编写的 Raspberry Pi 自定义命令

python-3.x - 使用pyspark从元组列表创建DataFrame

python - 抓取 PyQt 中的任何异常

python - 如何将元组列表转换为以索引为键的字典

php - 如何从 php.net 获取最新的 php 版本信息

python - 设置路径名中数字的格式

python - 使用 Python 查找文件列表中的重复次数

java - 从对象列表创建列表