简体   繁体   English

如何在python中使用raw_input将元组作为输入?

[英]How can I take tuple as input using raw_input in python?

I am trying to take input. 我正在尝试接受输入。 But it's not the correct syntax. 但这不是正确的语法。

a, b, c = (int(x) for x in raw_input().strip(' '))

My idea is to take multiple values from single line which has integers separated by space. 我的想法是从单行中获取多个值,这些值具有由空格分隔的整数。 How can I do it? 我该怎么做?

You were very close. 你非常接近。 It's split not strip : 这是split而不是strip

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

This will take exactly 3 integers, no more no less. 这将完全取3个整数,不多也不少。 If you want to take an arbitrary amount into a tuple, try this instead: 如果你想将任意数量转换为元组,请尝试以下方法:

tup = tuple(int(x) for x in raw_input().split())

I'm guessing you want the split function, not the strip function. 我猜你想要拆分功能,而不是条带功能。 That will return an array that you can iterate over. 这将返回一个可以迭代的数组。 The strip function will just remove initial and trailing characters (in your case spaces). strip函数将只删除初始和尾随字符(在您的情况下为空格)。

That will throw an exception if the user doesn't enter data in the correct format though. 如果用户没有以正确的格式输入数据,那将抛出异常。

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

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