Python reduce() 函數


Python reduce() 函數

在調用該函數之前,先要導入該函數from functools import reduce

def reduce(function, sequence, initial=None): # real signature unknown; restored from __doc__
    """
    reduce(function, sequence[, initial]) -> value
    
    Apply a function of two arguments cumulatively to the items of a sequence,
    from left to right, so as to reduce the sequence to a single value.
    For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
    ((((1+2)+3)+4)+5).  If initial is present, it is placed before the items
    of the sequence in the calculation, and serves as a default when the
    sequence is empty.
    """
    pass

通俗解釋:reduce(function, sequence): function是一個函數,sequence是一個數據集合(元組、列表等)。先將集合里的第1,2個參數參入函數執行,再將執行結果和第3個參數傳入函數執行....,最終得到最后一個結果

比如:reduce(lambda x, y: x + y,[1,2,3,4])執行步驟:

先將1,2傳入:1+2 = 3

再將3,3傳入:3+3 = 6

再將6,4傳入:6+4 = 10

最終結果為:10

習題

Python 一個數如果恰好等於它的因子之和,這個數就稱為"完數"。例如6=1+2+3.編程找出 1000 以內的所有完數

from functools import reduce
for i in range(2, 1001):
    l = [1]
    for j in range(2, int(i / 2 + 1)):
        if i % j == 0:
            l.append(j)
    if i == reduce(lambda x,y: x+y, l):
        print(i)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM