如何输入多个键,输出应该返回多个值.请检查脚本和我的评论


nestdic = { 'modelname' : {
'mod-num-1221' : 'LENEVO' ,
'mod-num-1222' : 'ASUS' ,
'mod-num-1223' : 'APPLE' ,
'mod-num-1224' : 'SAMSUNG' ,
'mod-num-1225' : 'HP'
}, 'ostype' : {
'LENEVO' : 'Windows' ,
'ASUS' : 'Windows' ,
'APPLE' : 'IOS' ,
'SAMSUNG' : 'LINUX' ,
'HP' : 'Windows'
} }
option = input("Please select from the below optionsn1. Vendor Name typen2. OS typennnPlease make a selection or press Q to quit: ")
if option == '1':
for i in range(5):
modelnum = input("Please enter the model num: ")
model = list(nestdic['modelname'])
if modelnum not in model:
print("Model name not found")
continue
modelname = nestdic['modelname'][modelnum]
if modelnum in model:
print("model name = " + modelname)
elif option == '2':
for i in range(5):
compname = input("Please enter the vendors name: ")
os = list(nestdic['ostype'])
if compname not in os:
print("os name not found")
continue
compsname = nestdic['ostype'][compname]
if compname in os:
print("OS type = " + compsname)

当我运行这个脚本时,它会询问我的选项。如果我选择型号,它会要求我输入型号。。。当我输入型号(键(时,它会给我型号名称(值(。。。目前,我只能给出一个输入,而只能得到一个输出。我想输入多个值并获得多个输出。输入=模块-1221、模块-1222、模块-1225输出=LENVO、ASUS、HP

这里有很多需要研究的地方。我对您的代码进行了其他一些修改,以纠正一些效率低下的问题;看看评论。

import re
nestdic = { 'modelname' : {
'mod-num-1221' : 'LENEVO' ,
'mod-num-1222' : 'ASUS' ,
'mod-num-1223' : 'APPLE' ,
'mod-num-1224' : 'SAMSUNG' ,
'mod-num-1225' : 'HP'
}, 'ostype' : {
'LENEVO' : 'Windows' ,
'ASUS' : 'Windows' ,
'APPLE' : 'IOS' ,
'SAMSUNG' : 'LINUX' ,
'HP' : 'Windows'
} }
option = input("Please select from the below optionsn1. Vendor Name typen2. OS typennnPlease make a selection or press Q to quit: ")
if option == '1':
models = nestdic['modelname'] # no reason for this to be in the loop and don't convert to list
while True: # loop while there is an error
error = False
modelnums_str = input("Please enter the model numbers separated by commas: ").strip()
if modelnums_str == '':
continue
modelnums = [modelnum for modelnum in re.split(r',s*', modelnums_str)]
modelnames = []
for modelnum in modelnums:
if modelnum not in models:
print(f'Model number {modelnum} not found.')
error = True
else:
modelnames.append(models[modelnum])
if error:
continue
if modelnames:
print(f"Input = {', '.join(modelnums)}, Output = {', '.join(modelnames)}")
break
elif option == '2':
os = nestdic['ostype'] # no reason for this to be in the loop and don't convert to a list
for i in range(5):
compname = input("Please enter the vendors name: ")
if compname not in os:
print("os name not found")
continue
compsname = os[compname]
print("OS type = " + compsname)

尝试使用4个空格进行缩进;8有点多。参见PEP 8——Python代码样式指南

最新更新