下面的代码显示了一个选项列表,用户可以选择输入一个数字。你知道吗
这是工作正常,但我不明白为什么选项似乎没有秩序。你知道吗
而不是:
1 - User Management
2 - Uploads
8 - Exit
我有:
1 - User Management
8 - Exit
2 - Uploads
你看到问题出在哪里了吗?你知道吗
Choice = namedtuple("Choice", ['msg', 'callback'])
def nav():
print ""
while True:
response_options = {'1': Choice(msg="User Management", callback=userManagment),
'2': Choice(msg="Uploads", callback=upload),
'8': Choice(msg="Exit", callback=sys.exit)}
result = make_choice(response_options)
if result is None:
print "-> Selected option not available."
print ""
else:
result.callback()
return False
def make_choice(optiontable):
for resp, choiceobj in optiontable.items():
print("{} - {}".format(resp, choiceobj.msg))
print ""
print "Select an option: "
print ""
usr_resp = raw_input(">> ")
print ""
return optiontable.get(usr_resp, None)
标准python字典是无序的。有关按键对词典排序的问题,请参见以下问题:How can I sort a dictionary by key?
相关问题 更多 >
编程相关推荐