高階関数 functools.reduce のよくある使用方法

以前、高階関数 functools.reduce(function, sequence, initial=None) を使った
リストの重複有無をチェックするを書いたけど、
oboe2uran.hatenablog.com

もっと、一般的なやさしい使い方を書いておこう。

collections namedtuple で定義したリストから合計値を求めるサンプル

# -*- coding: utf-8 -*-
from collections import namedtuple
import functools

Item = namedtuple("tool", ['name', 'value', 'mount'])

items = [
    Item('a', 200, 3),
    Item('b', 100, 2),
    Item('c', 300, 2)
]

total = functools.reduce(lambda a, b: a + b.value * b.mount, items, 0)

print("total = %d" % total)
print(items[0])
print(items[0].__class__.__name__)

結果

total = 1400
tool(name='a', value=200, mount=3)
tool