Suppose user enter this string at terminal
123 456 456 //then hit enter
How do I scan these three (could be more) numbers in different variables in python
Could be something like this:
for i in range(1,n)
m[i]=#WHAT FUNCTION SHOULD I PUT HERE
In c++ we can easily use cin>>m[i]
inside above loop to scan the variables.
If i use input()
or raw_input()
, they would scan whole line in single variable.
To get a list of these numbers, try
my_list = map(int, raw_input().split())
raw_input()
will return the verbatim string as you enter it. The split()
method of strings returns a list of strings split at any whitespace character. Finally, the map()
invocation turns this list of strings into a list of integers.
If you are using Python 3.x, use input()
instead of raw_input()
.
If you don't want to use a list, and you know the number of input values beforehand, you can use sequence unpacking to assign the values to different varaibles.
a, b, c = map(int, raw_input().split())
will work only if exactly three integers separated by whitespace are entered, and will assigne these three integers to the names a
, b
and c
.
if you do not want to scan the whole input in a list, you can write your own input parser, which reads one character at a time from the input stream:
def nextint(input):
def skip(input):
char = input.read(1)
while str.isspace(char):
char = input.read(1)
return char
char = skip(input)
while 1:
result = []
while str.isdigit(char):
result.append(char)
char = input.read(1)
yield int(str.join('', result))
char = skip(input)
now use it like this:
import sys
reader = nextint(sys.stdin)
for value in reader:
# process the value here
pass
(the generator will fail on the first block of non-space characters which cannot be converted to int)
cin
in the C++ runtime does the same. - Adrien Plisson
In Python 2.x:
m = [int(n) for n in raw_input().split()]
In 3.x:
m = [int(n) for n in input().split()]