这是我以前的问题here的更新版本。我正在添加到代码中,如果 get_close_matches 名称不是他们想要的人的姓名,则丢弃最接近的匹配并重新运行该函数并获取第二个最接近的匹配(现在首先,因为该函数会抛出出第一场比赛)。
你对如何写得更好有什么意见吗?和工作。>.>
这是我到目前为止所拥有的:
def throwout(pickedName):
employeeNames.remove(pickedName)
pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)
print(pickedName)
userNameOK = input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")
employeeNames = ['Colton','Jayne','Barb','Carlene','Dick','Despina']
employeeNames.sort()
userEmpName = input("Please enter the employee name you're searching for. We'll return the best match on record.")
pickedName = difflib.get_close_matches(userEmpName, employeeNames, 1)
print(pickedName)
userNameOK = input("Is this the name of the person you're looking for?\n\n Type 'Y' or 'N'.\n\n")
if userNameOK == "N" or "n":
if pickedName in employeeNames:
throwout(pickedName)
else:
break
else:
break
列表中的名称用完时出错:
Traceback (most recent call last):
File "C:/Python33/employee1.py", line 64, in <module>
print(userAnswer + " is the right choice.\n")
NameError: global name 'userAnswer' is not defined
我理解这意味着由于名称列表中没有更多名称可以将它们全部删除,因此全局变量“userAnswer”是未定义的。