【问题标题】:How to take either multiple or single input on one line from Python如何从 Python 的一行中获取多个或单个输入
【发布时间】:2022-10-23 21:09:43
【问题描述】:

要在一行上接受多个输入,我知道您可以执行以下操作:

a, b = input().split()

如果用户只输入 1 个输入,他们会遇到 ValueError:

“ValueError:没有足够的值来解包(预期 2,得到 1)”

因此,有没有一种方法可以让用户选择写入 1 个输入或两个输入,以便如果用户只有 1 个输入,变量 b 将被遗忘或替换为占位符?

【问题讨论】:

  • a = input().split() & 然后 assert len(a) <= 2

标签: python python-3.x


【解决方案1】:

老实说,最好的方法可能是收集列表并根据其长度采取行动。

现在,如果您真的想处理至少 1 个或 2 个(或更多),您可以使用打包/拆包:

a, *b = input().split()

print(f'first variable is {a}')
print(f'there is {"a" if b else "no"} second variable')
if b:
    print(f'second variable is {b[0]}')

示例 1:

x y

first variable is x
there is a second variable
second variable is y

示例 2:

x

first variable is x
there is no second variable

默认值:

a, *b = input().split()
b = next(iter(b), 'default')
print('variables:', a, b)

示例 1:

x y

variables: x y

示例 2:

x

variables: x default

【讨论】:

    【解决方案2】:

    将输入作为列表 IE。,

    lst = input().split()
    

    所以你不会得到值错误你可以稍后在索引的帮助下对用户输入进行更改 ... lst[0] ....

    这里发生了什么: input() 用于获取输入并将其存储在内存缓冲区中,然后再分配给变量 split() 获取变量或输入缓冲区中的值并根据空格对其进行拆分 input() 类似于 input(" ") 上面的代码也可以写成

    lst = input()
    lst = lst.split()```
    

    【讨论】:

    • input().split() 已经输出了一个列表...
    • str.split() 返回list
    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-14
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-03
    • 1970-01-01
    • 2015-12-14
    相关资源
    最近更新 更多