python中一个输入的两个值? [英] Two values from one input in python?

查看:28
本文介绍了python中一个输入的两个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个有点简单的问题,我不想在这里问它,但我似乎无法在其他任何地方找到答案:是否可以在一行 Python 中从用户那里获取多个值?

This is somewhat of a simple question and I hate to ask it here, but I can't seem the find the answer anywhere else: is it possible to get multiple values from the user in one line of Python?

例如,在 C 中,我可以这样做:scanf("%d %d", &var1, &var2).但是,我无法弄清楚 Python 的等价物是什么.我认为它就像 var1, var2 = input("Enter two numbers here:") 一样,但这不起作用,我没有抱怨,因为它不会成为一个整体如果确实如此,那就很有意义了.

For instance, in C I can do something like this: scanf("%d %d", &var1, &var2). However, I can't figure out what the Python equivalent of that is. I figured it would just be something like var1, var2 = input("Enter two numbers here: "), but that doesn't work and I'm not complaining because it wouldn't make a whole lot of sense if it did.

有没有人知道优雅而简洁地做到这一点的好方法?

Does anyone out there know a good way to do this elegantly and concisely?

推荐答案

Python 映射方式

The Python way to map

printf("Enter two numbers here: ");
scanf("%d %d", &var1, &var2)

应该是

var1, var2 = raw_input("Enter two numbers here: ").split()

请注意,我们不必明确指定 split(' ') 因为 split() 默认使用任何空白字符作为分隔符.这意味着如果我们简单地调用 split() 那么用户可以使用制表符分隔数字,如果他真的想要的话,也可以使用空格.,

Note that we don't have to explicitly specify split(' ') because split() uses any whitespace characters as delimiter as default. That means if we simply called split() then the user could have separated the numbers using tabs, if he really wanted, and also spaces.,

Python 具有动态类型,因此无需指定 %d.但是,如果您运行上面的代码,则 var1var2 都是字符串.您可以使用另一行

Python has dynamic typing so there is no need to specify %d. However, if you ran the above then var1 and var2 would be both Strings. You can convert them to int using another line

var1, var2 = [int(var1), int(var2)]

或者你可以使用列表理解

var1, var2 = [int(x) for x in [var1, var2]]

总而言之,你可以用这个单线完成整个事情:

To sum it up, you could have done the whole thing with this one-liner:

# Python 3
var1, var2 = [int(x) for x in input("Enter two numbers here: ").split()]

# Python 2
var1, var2 = [int(x) for x in raw_input("Enter two numbers here: ").split()]

这篇关于python中一个输入的两个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆