传递1 2 23 32 4在python的最大函数中返回4,为什么?

问题描述 投票:1回答:2

我的代码


def validate():
    if len(sys.argv) > 6:
        print("No more than 5 arguments please")
        exit()

def printArgs():
    print("\nthe arguments are:\n")

    for arg in sys.argv[1:]:
        print (arg)

def checkDigits():
    biggest = []
    for arg in sys.argv[1:]:
        if arg.isdigit():
            biggest.append(arg)

    if len(biggest)>= 3:
        print("\nthe biggest number passed is: ", max(biggest))
    else:
        print("you did not pass 3 or more numbers")

def main():

    validate()
    printArgs()
    checkDigits()

main()

如果我通过1 2 23 32 4,它在“checkDigit”函数中返回4而不是32,我不知道为什么。传球5 4 3 2 1回归5,所以我错过了什么?

我读了另一个StackOverflow帖子,并认为将key = int添加到我的max函数应该有效,对不对?

def checkDigits():
    biggest = []
    for arg in sys.argv[1:]:
        if arg.isdigit():
            biggest.append(arg)

    if len(biggest)>= 3:
        print("\nthe biggest number passed is: ", max(biggest, key=int))
    else:
        print("you did not pass 3 or more numbers")
python max command-line-arguments
2个回答
0
投票

在你的函数checkDigits中,你必须在“最大”列表中追加整数,所以改为:

def checkDigits():
    biggest = []
    for arg in sys.argv[1:]:
        if arg.isdigit():
            biggest.append(int(arg))

2
投票

您正在使用字符串列表的max。你需要转换为int

为了演示,这就是你正在做的事情:

max("1 2 23 32 4".split())
#'4'

这是你应该做的:

max(map(int, "1 2 23 32 4".split()))
#32

更新代码的自然地方是在附加到int时转换为biggest

def checkDigits():
    biggest = []
    for arg in sys.argv[1:]:
        if arg.isdigit():
            biggest.append(int(arg))  #THIS LINE IS CHANGED

    if len(biggest)>= 3:
        print("\nthe biggest number passed is: ", max(biggest))
    else:
        print("you did not pass 3 or more numbers")
© www.soinside.com 2019 - 2024. All rights reserved.