In Python, the default entry is visible as an open text file in the object sys.stdin
If the file was redirected from another, the end of file will be detected on sys.stdin
- without redirecting, as in the C++ example, the program is forever waiting for new lines.
Thus, a common file method such as readlines()
can automatically read all lines of standard input. What it doesn’t do is convert the read content to some type - Python, with all the expressiveness it has, doesn’t have many "magic" in the syntax - you can use a list comprehension or the function map
to convert all read lines to integer.
For example:
import sys
dados = map(int, sys.stdin)
Ready - just this - the map
asks for an iterable object in the second argument - a text file, when iterated, emits (yields) one line at a time. That line is passed to the flame int
, that despises white-space characters - including the newline that comes in the line vinal. In short: dados
becomes a generating object that can be used in a for
, or may be transformed into a list of dados = list(dados)
.
The syntax with list comprehension is:
import sys
dados = [int(linha) for linha in sys.stdin]
Axei the vague question, could put an example in c++, to make the analogy with python,
– Octávio Santana
friend edited the question.
– WLopesMTB