任意数量的用户输入到函数中

2024-09-29 19:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个Python函数,它接受任意数量的整数输入并返回LCM。我想让用户以友好的方式传递任意数量的输入,然后让我的函数计算它们。在

我已经找到了一种合理的方法,让用户一次传递一个整数并将它们附加到一个列表中,但是,我似乎无法让我的函数以列表或元组的形式来处理这个问题。在

这是我的代码:

#Ask user for Inputs
inputs = []
while True:
    inp = input("This program returns the LCM, Enter an integer,\
    enter nothing after last integer to be evaluated: ")
    if inp == "":
        break
    inputs.append(int(inp))

#Define function that returns LCM
def lcm(*args):
    """ Returns the least common multiple of 'args' """
    #Initialize counter & condition
    counter = 1
    condition = False

    #While loop iterates until LCM condition is satisfied
    while condition == False :
        counter = counter + 1
        xcondition = []
        for x in args:
            xcondition.append(counter % x == 0)
        if False in xcondition:
            condition = False
        else:
            condition = True
    return counter

#Execute function on inputs
result = lcm(inputs)

#Print Result
print(result)

Tags: 函数用户false列表for数量counterargs
2条回答

*args的思想是获取任意数量的参数,并将它们作为一个列表处理,以便于处理。在

但是只插入一个参数-列表。在

要么使用lcm(*inputs)(它将列表解压为不同的参数),要么只将列表作为参数(这意味着lcm被简单地定义为lcm(args))。在

你需要打开你的清单

result = lcm(*inputs)

但总的来说,我会说接受一个序列(listtuple,等等)参数要比担心*arg解包更具Python味。在

相关问题 更多 >

    热门问题