【发布时间】:2013-03-21 02:28:29
【问题描述】:
我可以在 Ruby 中使用
x = gets.split(" ").map{|x| x.to_i}
如何用 Python 编写
【问题讨论】:
标签: python
我可以在 Ruby 中使用
x = gets.split(" ").map{|x| x.to_i}
如何用 Python 编写
【问题讨论】:
标签: python
x = [int(part) for part in input().split()]
在 2.x 中,使用 raw_input() 而不是 input() - 这是因为在 Python 2.x 中,input() 将用户的输入解析为 Python 代码,这既危险又缓慢。 raw_input() 只是给你字符串。在 3.x 中,他们更改了 input() 以按照您通常想要的方式工作。
这是一个简单的list comprehension,它采用输入的拆分组件(使用str.split(),它在空格上拆分)并使每个组件成为整数。
【讨论】:
在 python 3.x 中
list(map(int, input().split()))
在 python 2.x 中
map(int, raw_input().split())
【讨论】:
map() 也是一个非常好的方法。
>>> x = raw_input("Int array")
Int array>? 1 2 3
>>> map(int, x.split())
[1, 2, 3]
【讨论】: