在 Python 中读取一行整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15963959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a line of integers in Python
提问by kunal18
I am beginner in Python and I am solving a question at CodeChef where I have to read a line of space separated integers. This is what I am doing:
我是 Python 初学者,我正在 CodeChef 解决一个问题,我必须读取一行空格分隔的整数。这就是我正在做的:
def main():
t=int(raw_input()) #reading test-cases
while t!=0:
n, k=raw_input().split() #reading a line of two space separated integers
n, r=int(n), int(r) #converting them into int
list=[]
#reading a line of space separated integers and putting them into a list
list[-1:101]=raw_input().split()
Now I to convert each element in the list to integer. Is there some better way to to do this? Please suggest an online resource where I can play with Python and learn tips and tricks!
现在我将列表中的每个元素转换为整数。有没有更好的方法来做到这一点?请推荐一个在线资源,我可以在其中使用 Python 并学习技巧和窍门!
采纳答案by NPE
In Python 2, you could write:
在 Python 2 中,你可以这样写:
numbers = map(int, raw_input().split())
This reads a line, splits it at white spaces, and applies int()to every element of the result.
这会读取一行,在空白处将其拆分,并应用于int()结果的每个元素。
If you were using Python 3, the equivalent expression would be:
如果您使用的是 Python 3,则等效的表达式为:
numbers = list(map(int, input().split()))
or
或者
numbers = [int(n) for n in input().split()]
回答by Mayank Jain
map(int, list)should solve your problem
map(int, list)应该能解决你的问题

