簡體   English   中英

如何從 Python 在一條線上獲取多個或單個輸入

[英]How to take either multiple or single input on one line from Python

要在一行上接受多個輸入,我知道您可以執行以下操作:

a, b = input().split()

如果用戶只輸入 1 個輸入,他們會遇到 ValueError:

“ValueError:沒有足夠的值來解包(預期 2,得到 1)”

因此,有沒有一種方法可以讓用戶選擇寫入 1 個輸入或兩個輸入,以便如果用戶只有 1 個輸入,變量 b 將被遺忘或替換為占位符?

老實說,最好的方法可能是收集列表並根據其長度采取行動。

現在,如果您真的想處理至少 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

您可能可以使用列表推導,然后對返回的列表運行一些檢查。

lst = [input for input in input().split()]

將輸入作為列表,即

lst = input().split()

所以你不會得到值錯誤你可以稍后在索引的幫助下對用戶輸入進行更改... lst [0] ....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM