0

In Ruby I can use

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

how to write in Python

sawa
  • 165,429
  • 45
  • 277
  • 381
lifez
  • 318
  • 1
  • 4
  • 9

3 Answers3

7

In python 3.x

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

In python 2.x

map(int, raw_input().split())
awesoon
  • 32,469
  • 11
  • 74
  • 99
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
  • 86,389
  • 17
  • 178
  • 183
3
>>> x = raw_input("Int array")
Int array>? 1 2 3
>>> map(int, x.split())
[1, 2, 3]
garnertb
  • 9,454
  • 36
  • 38