【问题标题】:Python Input with operators and integers带有运算符和整数的 Python 输入
【发布时间】:2023-02-04 15:17:00
【问题描述】:

如何使用 python 中的 map 函数在同一行输入 2 个整数和 1 个运算符

1 2 +

我做了 a, b, c = map(int, input().split())

但是它打印了Traceback (most recent call last): File "main.py", line 2, in <module> a, b, c = map(int, input().split()) ValueError: invalid literal for int() with base 10: '+'

【问题讨论】:

  • 这听起来根本不像是 map 的工作。
  • 你能告诉我应该使用什么命令吗
  • 为什么要为此使用map
  • 只需使用 split 并分别投射前两个元素。 a, b, op = input.split() 然后投射ab
  • map 的全部意义在于每个人都一样输入的。这不是你想要的。没有任何“命令”(这不是正确的词,顺便说一句)可以为您执行此操作,因为您需要执行一些自定义操作。

标签: python


【解决方案1】:

我可能会这样做:

*ab, c = input().split()
a, b = map(int, ab)

忍不住,太好玩了:

input = lambda: '1 2 +'

stack = []
stack += map(
    lambda s: int(s) if s.isdigit() else stack.pop() + stack.pop(),
    input().split()
)
print(*stack)

输出(Try it online!):

3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 1970-01-01
    • 2013-12-12
    • 2012-12-30
    相关资源
    最近更新 更多