【问题标题】:How to get more than one input from a single input() function in Python?如何从 Python 中的单个 input() 函数获取多个输入?
【发布时间】:2020-02-23 15:01:21
【问题描述】:

我了解到,在自定义函数参数之前使用 *,我可以传递多个或不确定数量的数据作为参数。对于添加数字功能或类似的功能,我可以在调用该功能时传递无限量的数据。但我想从用户那里得到这些数字。因为我不知道我会得到多少个数字,所以我以前不能为每个数字声明变量。现在,我怎样才能获得许多数字作为输入并将它们与自定义函数相加?我的想法与现实生活中的计算器非常相似。

这是我的代码。我想将数字作为输入,而不是在编写代码时手动输入。如果有人给我有关我正在尝试做的事情的代码,我将不胜感激。

def add_number(*args):
    total = 0
    for number in args:
        total += number
    print(total)


add_number(2, 3, 6, 9)

【问题讨论】:

  • 到目前为止你尝试了什么?
  • print(sum(map(float, input("输入数字...").split())))
  • 你可以用sum(...)代替add_number(...)

标签: python function input arguments


【解决方案1】:

您说您需要使用单个输入。在这种情况下,我们可以使用字符串的.split(separator) 方法拆分输入,该方法返回给定字符串的部分列表。 separator 参数是可选的:如果用户输入的是空格字符分隔的数字,则不需要传递此参数,否则需要传递分隔符。

numbers = input("Enter the numbers... ").split()  # if numbers are separated by any of whitespace characters ("1 2 3 4")
numbers = input("Enter the numbers... ").split(", ")  # if numbers are separated by a comma and a space ("1, 2, 3, 4")

注意:我假设您的数字在答案的下一部分用空格字符分隔。

如果我们想打印numbers 列表,我们会得到这个输出:

>>> numbers = input("Enter the numbers... ").split()
Enter the numbers... 1 2 3 4
>>> print(numbers)
['1', '2', '3', '4']

我们可以看到列表中的所有项目都是字符串(因为引号:'1',而不是1)。如果我们尝试将它们连接在一起,我们将得到如下结果:'1234'。但是,如果您想将它们作为数字而不是字符串连接在一起,我们需要将它们转换为 int(对于整数)或 float(对于非整数)类型。如果我们有一个号码,就可以轻松完成:int(number)。但是我们有数字列表,我们需要将每个元素转换为int

我们可以使用map(func, iterable) 函数。它将func 应用于iterable 的每个项目并返回一个map 对象 - 一个迭代器(不是列表!)

numbers = map(int, numbers)

注意:如果我们想将它表示为一个列表,我们可以简单地这样做:

numbers = list(map(int, numbers))

虽然这里没有必要。

现在我们可以使用星号 (*) - pack 将所有数字扔给您的 add_number(*args) 函数:

add_number(*numbers)

注意:您还可以使用sum 函数将所有可迭代的数字相加 - 在这种情况下,您不需要打包 args,因为它会得到一个可迭代的数字:

sum_ = sum(numbers)

然后让我们print我们的结果:

print(sum_)

重要提示: sum(iterable) 返回数字的总和并且不打印任何内容,而您的 add_number(*args) 函数返回 None 并打印数字(这不是一回事!)。 Here 是一个很好的详细解释。

这是我们编写的全部代码:

def add_number(*args):
    total = 0
    for number in args:
        total += number
    print(total)

numbers = input("Enter the numbers... ").split()  # if numbers are separated by any of whitespace characters ("1 2 3 4")
numbers = map(int, numbers)
add_number(*numbers)

这是一个做同样事情的单行代码 - 它使用 sum 函数而不是 add_number,因此不需要代码中的任何其他内容:

print(sum(map(int, input("Enter the numbers... ").split())))

【讨论】:

  • 非常感谢您提供如此详细的回答。这对我帮助很大。 ?
  • @HMKhalidMahmud,我很高兴能帮助你! :)
猜你喜欢
  • 1970-01-01
  • 2022-10-23
  • 2012-06-14
  • 2015-12-04
  • 2021-10-21
  • 2018-06-03
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
相关资源
最近更新 更多