30秒学会 Python 片段 · 2023年11月29日

30秒学会 Python 片段 – Weighted average

Returns the weighted average of two or more numbers.

  • Use sum() to sum the products of the numbers by their weight and to sum the weights.
  • Use zip() and a list comprehension to iterate over the pairs of values and weights.

代码实现

def weighted_average(nums, weights):
  return sum(x * y for x, y in zip(nums, weights)) / sum(weights)

使用样例

weighted_average([1, 2, 3], [0.6, 0.2, 0.3]) # 1.72727

翻译自:https://www.30secondsofcode.org/python/s/weighted-average