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

查看:137
本文介绍了来自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都是字符串.您可以使用另一行将它们转换为int

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天全站免登陆