如何动态获取用户的输入数量?

时间:2018-03-05 08:27:25

标签: python

我从用户那里得到多个输入,我无法测量,如何动态读取所有输入。

例如

a,b = input(),input()

我们只能获得两个输入但我想一次获取多个输入,而不知道我们得到的输入数量。

我的输入是

3
11
1 2 -1 4 0 5 -3 8 7 0 10
10
1 2 -1 4 0 5 -3 8 7 10
5
1 2 3 4 5
.
.
etc
每个输入的每一行

3 个答案:

答案 0 :(得分:0)

  输入格式

lines = []
while True:
  line = list(map(int,input().split()))
  if line:
    lines.append(line)
  else:
    break
print(lines)

输入:

3
11
1 2 -1 4 0 5 -3 8 7 0 10
10
1 2 -1 4 0 5 -3 8 7 10
5
1 2 3 4 5

输出

[[3], 
 [11], 
 [1, 2, -1, 4, 0, 5, -3, 8, 7, 0, 10], 
 [10], 
 [1, 2, -1, 4, 0, 5, -3, 8, 7, 10],
 [5], 
 [1, 2, 3, 4, 5]]
  

对于单行输入

inputnumbers=list(map(int,input("Input:").split()))
print("Output",inputnumbers)
print("input[3]",inputnumbers[3])

输出

Input: 1 2 3 4 5
Output [1, 2, 3, 4, 5]
input[3] 4
  

对于multiLine

lines = []
while True:
  line = input()
  if line:
    lines.append(line)
  else:
    break
print(lines)

输入:

1 2 3 4 5
asdf asdf asdf
1234

输出:

['1 2 3 4 5', 'asdf asdf asdf', '1234']

答案 1 :(得分:0)

如果没有某种方式表示何时停止从标准输入读取,这是不可能的。例如。 Python需要知道何时停止阻塞等待标准输入并继续执行其余代码。

正如一些人所建议的那样,你可以在一行中使用逗号或空格等分隔符来获取所有输入。

或者,你可以使用一个特殊字符,例如换行符或只有空格(或其他一些魔术字符串)的行作为python的提示,以停止从标准读取,例如。

inputs = []
while True:
    next_input = input()
    if not next_input.strip():
        break
    inputs.append(next_input)

答案 2 :(得分:0)

您可以在循环中阅读input(),并将返回的值附加到列表values

当用户点击Ctrl + D时,End of File将被发送到Python,引发EOFError。当用户按Ctrl + C时,它会发送KeyboardInterrupt。我们都可以用来表示我们已经读完了数字。

values = []
while True:
    try:
        values.append(input())
    except (EOFError, KeyboardInterrupt):
        break

print(values)

以这种方式捕获EOF的优势在于我们还可以将其他流或文件重定向到我们的循环中,并且可以识别重定向文件的末尾:使用文件inputs,如

1
2
3
hello

你可以做到

cat inputs | python test.py

并获取

['1', '2', '3', 'hello']
相关问题