【问题标题】:Enter multiple numbers on the same line without using a list in Python [duplicate]在同一行输入多个数字而不使用Python中的列表[重复]
【发布时间】:2020-01-04 08:30:48
【问题描述】:

我需要在 Python 的同一行中输入n 多个整数,而不使用列表或任何其他容器(set、dict 等)(请不要问我为什么,假设我必须这样做,这就是那个问题的重点)。

我知道在 C++ 中你可以这样写:

int how_many_numbers, number;
cin >> how_many_numbers;
for (int i = 0; i < how_many_numbers; i++) {
    cin >> number;
    // do something with it
}

cin 最酷的地方在于它没有说明如何输入数字:您可以输入一个数字并按回车键,然后您可以在同一行输入 3 个数字并按再次输入,然后再输入 2 或 4,依此类推,直到您输入所有必须输入的数字。

我的问题是:在 Python 中是否有类似 cin 的东西可以让我在同一行输入多个整数 n 而无需使用列表或任何其他容器?

感谢您的帮助。

【问题讨论】:

  • 我不明白你想要达到什么目的。例如,如果您想将3 1 2 4 加载到3 数字:124 为什么不使用numbers = input().split(" ")?然后numbers[0] 包含你有多少个数字,numbers[1:] 是那些数字。在其他方面,您可能需要使用非标准库。
  • 您的评论编号中的@ventaquil 是一个列表,我想避免使用它。
  • 所以你必须使用非标准库才能从终端逐字符加载数据。
  • @ventaquil 我想是的。请问有哪些图书馆可以推荐?

标签: python cin


【解决方案1】:

在您提供的代码中,您没有存储数组:实际上您只是存储了最后输入的数字,即使您处于循环中。

以下是 C++ 代码和匹配的 Python 代码。两者都不存储单个输入的值..它们只存储最后一个值。如果要存储每个值,我认为需要某种数据结构。

提供的C++程序

int how_many_numbers, number; 
cin >> how_many_numbers; 
for (int i = 0; i < how_many_numbers; i++) 
{ cin >> number; 
// do something with it 
}

Python 等价物

how_many_numbers, number = 0, 0
how_many_numbers = input()
for (i in range(how_many_numbers)):
    number=input()
    # do something with it

希望这会有所帮助。

【讨论】:

  • input() 在 Python 中的工作方式与 C++ 中的 cin 在空格和按下回车按钮方面的工作方式不同。
  • @alekscooper 是的,你是对的。在 C++ 中,如果您编写多个输入(当您声明一个 int 时),在我看来,first 之后的所有其他条目都将被忽略。在 python 中,无论您键入多少个数字,所有内容都会被存储,因为整行都存储为字符串。我以为你想要最接近 C++ 代码的 Python 对应物。很抱歉误读了这个问题。
猜你喜欢
  • 2021-11-11
  • 2022-08-21
  • 1970-01-01
  • 2015-04-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多