简体   繁体   English

在python中使用for循环获取输入

[英]Taking input using for loop in python

a,b = int(i) for i in input().split()

Can someone explain why the above code doesn't work? 有人可以解释为什么上面的代码不起作用吗?

I understand I can use this to make a list like: 我了解我可以使用它来制作类似以下的列表

a = [int(i) for i in input().split()]

But why doesn't it work for 2 values? 但是为什么它不适用于2个值? If a runtime exception rises(passing more than 2 values), termination is totally legit. 如果运行时异常上升(传递两个以上的值),则终止是完全合法的。 But the shows invalid syntax. 但是显示语法无效。

I just checked. 我刚刚检查。 These are called Generator Functions . 这些称为生成器函数 And the code can be modified as: 并且代码可以修改为:

a,b = (int(x) for x in input().split())

Also, a,b = [int(x) for x in input().split()] also does the same job, but instead it return a list. 同样, a,b = [int(x) for x in input().split()]也做同样的工作,但是它返回一个列表。 The list is then iterated and is assigned to the variables at python's end. 然后迭代该列表,并将其分配给python末尾的变量。 (Correct me if I am wrong) (如果我做错了,请纠正我)

Thanks to everyone who answered! 感谢所有回答! :D :d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM