[英]How to take multiple multiline input variables in Python?
Is it possible to take multiple newline inputs into multiple variables & declare them as int
all at once?是否可以将多个换行符输入到多个变量中并一次将它们声明为int
?
To explain further what I am trying to accomplish, I know this is how we take space separated input using map:为了进一步解释我要完成的任务,我知道这就是我们使用 map 获取空格分隔输入的方式:
>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5
Is there an equivalent for a newline?换行符有等价物吗? Something like:就像是:
a, b = map(int, input().split("\\n"))
Rephrasing: I am trying to take multiple integer inputs, from multiple lines at once.改写:我试图一次从多行中获取多个整数输入。
As others have said it;正如其他人所说; I don't think you can do it with input()
.我认为你不能用input()
做到这一点。
But you can do it like this:但是你可以这样做:
import sys
numbers = [int(x) for x in sys.stdin.read().split()]
Remeber that you can finish your entry by pressing Ctrl+D
, then you have a list of numbers, you can print them like this (just to check if it works):请记住,您可以通过按Ctrl+D
完成输入,然后您就有了一个数字列表,您可以像这样打印它们(只是为了检查它是否有效):
for num in numbers:
print(num)
Edit: for example, you can use an entry like this (one number in each line):编辑:例如,您可以使用这样的条目(每行一个数字):
1
543
9583
0
3
And the result will be: numbers = [1, 543, 9583, 0, 3]
结果将是: numbers = [1, 543, 9583, 0, 3]
Or you can use an entry like this:或者您可以使用这样的条目:
1
53 3
3 4 3
54
2
And the result will be: numbers = [1, 53, 3, 4, 3, 54, 2]
结果将是: numbers = [1, 53, 3, 4, 3, 54, 2]
From what I understand from your question,you want to read the input until EOF
character is reached and extract the numbers from it:从我从您的问题中了解到,您想读取输入直到达到EOF
字符并从中提取数字:
[ int(x.strip()) for x in sys.stdin.read().split() ]
It stop once ctrl+d
is sent or the EOF
characted on the entry is reached.一旦发送ctrl+d
或达到条目上的EOF
字符,它就会停止。
For example, this entry:例如,这个条目:
1 43 43
434
56 455 34
434
[EOF]
Will be read as: [1, 43, 43, 434, 56, 455, 34, 434]
将读作: [1, 43, 43, 434, 56, 455, 34, 434]
You really cannot, input
and raw_input
stop reading and return when a new line is entered;你真的不能, input
和raw_input
停止读取并在输入新行时返回; there's no way to get around that from what I know.据我所知,没有办法解决这个问题。 From input
s documentation :从input
的文档:
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.然后该函数从输入中读取一行,将其转换为字符串(去除尾随的换行符),然后返回该字符串。
A viable solution might be calling input
in a loop and joining on '\\n'
afterwards.一个可行的解决方案可能是在循环中调用input
,然后在'\\n'
上加入。
a, b = (int(input()) for _ in range(2))
如果您有从多个输入读取多个变量的意思:
a, b, c = map(int, (input() for _ in range(3)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.