用法:
functools.reduce(function, iterable[, initializer])將兩個參數的
function從左到右累積應用到iterable的項目,以將可迭代減少為單個值。例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])計算((((1+2)+3)+4)+5)。左側參數x是累積值,右側參數y是來自iterable的更新值。如果存在可選的initializer,則在計算中將其放置在可迭代項之前,並在可迭代項為空時用作默認值。如果沒有給出initializer並且iterable隻包含一個項目,則返回第一個項目。大致相當於:
def reduce(function, iterable, initializer=None): it = iter(iterable) if initializer is None: value = next(it) else: value = initializer for element in it: value = function(value, element) return value有關產生所有中間值的迭代器,請參見
itertools.accumulate()。
相關用法
- Python functools.wraps用法及代碼示例
- Python functools.singledispatchmethod用法及代碼示例
- Python functools.singledispatch用法及代碼示例
- Python functools.partial用法及代碼示例
- Python functools.partialmethod用法及代碼示例
- Python functools.cache用法及代碼示例
- Python functools.lru_cache用法及代碼示例
- Python functools.cached_property用法及代碼示例
- Python functools.total_ordering用法及代碼示例
- Python functools.wraps()用法及代碼示例
- Python dict fromkeys()用法及代碼示例
- Python frexp()用法及代碼示例
- Python float轉exponential用法及代碼示例
- Python calendar firstweekday()用法及代碼示例
- Python fsum()用法及代碼示例
- Python float.is_integer用法及代碼示例
- Python format()用法及代碼示例
- Python calendar formatmonth()用法及代碼示例
- Python filecmp.cmpfiles()用法及代碼示例
注:本文由純淨天空篩選整理自python.org大神的英文原創作品 functools.reduce。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
