0

In Ruby I can use

   x = gets.split(" ").map{|x| x.to_i}

how to write in Python

sawa
  • 160,959
  • 41
  • 265
  • 366
lifez
  • 318
  • 1
  • 4
  • 9

3 Answers3

6
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.

Gareth Latty
  • 82,334
  • 16
  • 175
  • 177
5

In python 3.x

list(map(int, input().split()))

In python 2.x

map(int, raw_input().split())
awesoon
  • 30,028
  • 9
  • 67
  • 92
3
>>> x = raw_input("Int array")
Int array>? 1 2 3
>>> map(int, x.split())
[1, 2, 3]
garnertb
  • 9,250
  • 33
  • 38