0

In Ruby I can use

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

how to write in Python

4

3 回答 3

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.

于 2013-03-30T13:57:27.207 回答
5

In python 3.x

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

In python 2.x

map(int, raw_input().split())
于 2013-03-30T13:59:47.610 回答
3
>>> x = raw_input("Int array")
Int array>? 1 2 3
>>> map(int, x.split())
[1, 2, 3]
于 2013-03-30T13:59:51.853 回答