簡體   English   中英

為什么以下使用 max() 的 python 代碼以一種方式工作而不是另一種方式?

[英]Why does the following python code using max() work one way but not another?

我正在做 exercism.io python 測試用例,所以我是這門語言的新手。
將導致整數的函數傳遞給 max() 函數是否存在問題?

蟒蛇 3

此代碼不起作用:
錯誤消息是 TypeError: 'int' object is not callable,
如果 max 函數的參數不完全是兩個,那么您會收到錯誤消息。
注意:無論我在 max 函數中包含還是排除了 (int),代碼都會失敗。

calculate_single 函數返回整數列表的乘積。

數字是數字列表的列表。

    ...
    largest = 0
    for digitlist in digits:
        largest = max((int)(calculate_single(digitlist)),largest)
    return largest

def calculate_single (digitlist):  
    current = 1  
    for digit in digitlist:  
        current *= (int)(digit)  
    return current

這段代碼確實有效。 我只想知道為什么第一個不起作用。

    ...
    largest = 0
    for digitlist in digits:
        largest = calculate_single(digitlist,largest)
    return largest

def calculate_single (digitlist,largest):
    current = 1
    for digit in digitlist:
        current *= (int)(digit)
    return max(current,largest)

我嘗試了你的代碼的兩個版本,似乎都很好。 版本 1:

def calculate_single(digitlist, largest):
    current = 1
    for digit in digitlist:
    current *= (int)(digit)
    return max(current, largest)

def calculate(digits):
    largest = 0
    for digitlist in digits:
        #print (largest)
        largest = calculate_single(digitlist, largest)
        #print (largest)
    return largest

if __name__ == '__main__':
    lst = [[2, 5, 7, 4.2, 3], [3.6, 6, 4, 2, 1], [5, 5, 5, 10,10]]
    big = calculate(lst)
    print(big)

版本 2:

def calculate_single(digitlist):
    current = 1
    for digit in digitlist:
        current *= (int)(digit)
    return current

def calculate(digits):
    largest = 0
    for digitlist in digits:
        #print (largest)
        largest = max((calculate_single(digitlist)), largest)
        #print (largest)
    return largest

if __name__ == '__main__':
    lst = [[2, 5, 7, 4.2, 3], [3.6, 6, 4, 2, 1], [5, 5, 5, 10,10]]
    #lst = [2, 3, 5, 8]
    big = calculate(lst)
    print(big)

我認為最重要的是 digitlist 是一個數字列表,digits 是一個列表列表。 所以一個列表應該傳遞給calculate_single(),一個列表應該傳遞給calculate()。 如果一個列表被傳遞給calculate(),它會引發TypeError。 在兩個版本中 max() 似乎都不錯,無論是否使用 int()

在 python 中轉換為int是通過以下方式完成的: int( )而不是(int)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM