In Ruby I can use
x = gets.split(" ").map{|x| x.to_i}
how to write in Python
x = [int(part) for part in input().split()]
In 2.x, use raw_input()
instead of input()
- this is because in Python 2.x, input()
parses the user's input as Python code, which is dangerous and slow. raw_input()
just gives you the string. In 3.x, they changed input()
to work that way as it is what you generally want.
This is a simple list comprehension that takes the split components of the input (using str.split()
, which splits on whitespace) and makes each component an integer.
In python 3.x
list(map(int, input().split()))
In python 2.x
map(int, raw_input().split())
>>> x = raw_input("Int array")
Int array>? 1 2 3
>>> map(int, x.split())
[1, 2, 3]