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,但我不太明白。此外,如果您完全像这样输入textta和textB,我想知道键和值是否会继续存储在字典数据库中。由于输入格式无条件为Command、textta和textB,因此有很多限制。我想我必须用一个重复的句子来组织它,但我想知道是否有其他方法。
我认为你是一个python初学者,因为在你的代码中有些东西出错了,因为我理解你的意图:
- 注释文本使用#,而不是//
- 使用变量直接命名它们,不要使用引号,引号是用于字符串的
- 你应该使用带下划线的小写变量名(PEP Styleguide)
要解决分裂问题,可以使用列表保存数据,然后从列表中弹出项,并使用try catch块,只捕获IndexError
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!"))
)
您可以使用额外的空字符串填充分割文本,以便解包始终有效:
Command, textA, textB, *_ = input().split(',')+['','']
试试这个:
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)