database = {}
while True:
print("Pleas type like Command,textA,textB")
Command, textA, textB = input().split(',')
if Command == 'PUT': // ex: PUT,a,c PUT is command to a is key, c is value
database[textA] = textB
print("Success!")
elif Command == 'GET': // ex: GET,a GET is command to get a's value
if "textA" in database:
print(database.get('textA'))
else:
print("Not exist!")
elif Command == 'DELETE': // ex: DELETE,a DELETE is command to delete a's key&value
if "textA" in database:
del database['textA']
print("Success!")
else:
print("Not exist!")
elif Command == 'LIST':
if "textA" in database:
for KEY, VALUE in database.items():
print(KEY, VALUE)
else:
print("Not exist!")
我想接收字典中的命令和鍵值,并根據每個命令操作if陳述句。但是,if 陳述句僅在無條件接收到三個值時才起作用,因此不能使用 GET、DELETE 和 LIST。我正在嘗試使用 TRY 和 EXCEPT,但我不太明白。此外,如果您完全這樣輸入 textA 和 textB,我想知道 Key 和 Value 是否會繼續存盤在字典資料庫中。有很多限制,因為輸入格式無條件是Command、textA和textB。我想我必須用一個重復的句子來組織它,但我想知道是否有另一種方式。
uj5u.com熱心網友回復:
我認為你是一個 python 初學者,因為我理解你的意圖,你的代碼中出現了一些錯誤:
- 注釋文本使用#,而不是//
- 要使用變數直接命名它們,不要使用引號,引號用于字串
- 您應該使用帶下劃線的小寫變數名(PEP 樣式指南)
為了解決拆分問題,您可以使用串列來保存資料,然后從串列中彈出專案并使用僅捕獲 IndexError 的 try catch 塊
database = {}
while True:
print("Pleas type like Command,textA,textB")
in_data = input().split(',') # Save into list
Command = in_data.pop(0) # Take 1 element
textA = in_data.pop(0) # Take 1 element
try:
textB = in_data.pop(0) # Take 1 element ..
except IndexError: # .. if available
textB = None
if Command == 'PUT': # ex: PUT,a,c PUT is command to a is key, c is value
database[textA] = textB
print("Success!")
elif Command == 'GET': # ex: GET,a GET is command to get a's value
if textA in database:
print(database.get(textA))
else:
print("Not exist!")
elif Command == 'DELETE': # ex: DELETE,a DELETE is command to delete a's key&value
if textA in database:
del database[textA]
print("Success!")
else:
print("Not exist!")
elif Command == 'LIST':
if textA in database:
for KEY, VALUE in database.items():
print(KEY, VALUE)
else:
print("Not exist!")
另外,您應該檢查您的輸入(例如,輸入正確的型別),為了更安全,您可以為 dict.get ( print(database.get(textA, "Not exist!")))定義默認值
uj5u.com熱心網友回復:
您可以使用額外的空字串填充拆分文本,以便解包始終有效:
Command, textA, textB, *_ = input().split(',') ['','']
uj5u.com熱心網友回復:
嘗試這個:
from itertools import zip_longest
text = input().split(',')
Command, textA, textB = dict(zip_longest(range(3),text)).values()
或這個:
from itertools import zip_longest
from types import SimpleNamespace
text = input().split(',')
params = SimpleNamespace(**dict(zip_longest(['Command', 'textA', 'textB'],text)))
# test
print(params.Command)
print(params.textA)
print(params.textB)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/347803.html
