【问题标题】:Multiple variables from single line in Python?Python中单行的多个变量?
【发布时间】:2012-04-15 04:19:38
【问题描述】:

我试图弄清楚“输入表达式:”之类的内容如何包含 3 个变量:第一个 int、操作字符和第二个 int。这在 C++ 中非常简单,只需 cin >> num1 >> operation >> num2。

到目前为止,根据其他人的问题,我已尝试将其纳入列表并将其拆分。这有效,除了超过 1 位的整数。我正在做这样的事情:

list1=raw_input()
list1.split()
print list1
num1=list1[0]
plus=list1[1]
num2=list1[2]
print num1, plus, num2

例如,输入 10+3 将输出 1 0 + 我觉得这里有一个简单的解决方法,但我不知道。任何帮助表示赞赏。

【问题讨论】:

    标签: python input


    【解决方案1】:

    字符串是不可变的,因此您需要在某处捕获list1.split() 的结果。但它不会帮助你,因为那不会做你想要的。使用解析器,可能使用Python's language services。

    【讨论】:

      【解决方案2】:

      试试这个:

      list1 = raw_input()
      for x in list1.split():
          print x,
      

      【讨论】:

      • @IgnacioVazquez-Abrams 那里,修好了。
      • IndexError 消失了,但这仍然不能满足提问者的要求。
      【解决方案3】:

      我建议在这种情况下使用正则表达式,例如:

       re_exp = re.compile(r'\s*(\d+)\s*([^\d\s])+\s*(\d+)')
       expr = raw_input()
       match = re_exp.match(expr)
       if match:
           num1, oper, num2 = match.groups()
           print num1, oper, num2
      

      使用split,您可以解析10 + 1,但使用10+1(不带空格)或同时处理这两种情况会更难。

      【讨论】:

      • 是的,我刚刚意识到这一点。谢谢!它只适合我(程序),所以我不需要处理空间不足的问题。
      【解决方案4】:
      #You should write like this
      list1 = raw_input()
      a=list1.split()
      num1=a[0]
      plus=a[1]
      num2=a[2]
      print num1, plus, num2
      

      【讨论】:

      • 嗨,欢迎来到 SO。如果你能解释你的代码并举例说明为什么 op“应该这样写”,那就太好了。
      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2012-06-12
      • 2014-12-08
      • 2013-01-04
      • 2020-09-20
      • 2020-05-04
      相关资源
      最近更新 更多