【发布时间】:2012-04-17 01:33:51
【问题描述】:
所以我有一个 Python 任务,我需要使用字典来保存菜单项,然后随机重新键入并重新排序菜单,以便我可以更改打印出来的菜单选项的顺序。这是我的代码示例:
ChoiceOne = "Rekey Menu"
ChoiceTwo = "Quit"
menu = {'1':ChoiceOne, '2':ChoiceTwo,}
userChoice = input("Please Enter the Integer for Your Menu Choice: ")
while userChoice not in menu.keys():
print("Invalid Input")
userChoice = input("Please Enter the Integer for Your Menu Choice: ")
if menu[userChoice] == ChoiceOne:
menu = rekey(menu)
elif menu[userChoice] == ChoiceTwo:
quit()
上面的代码在用户选择不退出时循环,一遍又一遍地打印出菜单。以下是我的 rekey() 函数
def rekey(menu):
rekey = {}
keylist = random.sample(range(10), 2)
for i, item in zip(keylist, menu ):
rekey[i] = menu[item]
return rekey
我的问题似乎出现在我检查菜单选项的用户输入是否有效的行中。最初,输入“1”或“2”以外的任何内容都会导致程序进入 While 循环,直到输入有效输入。然而,在重新输入菜单后,“当 userChoice 不在 menu.keys() 中时”行总是被触发,并且没有匹配的输入来继续程序。
我试图通过打印字典中的新键并检查 userChoice 是否与其中任何一个匹配来找到问题,但即使我选择了一个有效的新键,程序似乎也认为什么都没有我输入的是一个有效的密钥。
我希望我已经把问题描述得足够好,以便理解,提前感谢您的帮助!
【问题讨论】:
-
无视我的回答。我想了一会儿,意识到这是完全错误的。请投票 2 删除。
-
对
menu[userChoice]的检查应该在 while 循环内(即在发布期间搞砸了)还是在外面?如果是后者,那么我看不到在重新键入后再次提示的外部循环... -
您可以在
rekey()中更简单地构建字典:return dict(zip(random.sample(range(10), 2), menu))。或者更确切地说,解决问题:return dict(zip(map(str, random.sample(range(10), 2)), menu))。 ;)
标签: python random dictionary