使用原始Inpu访问字典

2024-06-03 01:16:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让一个用户输入1,2,3,4,5,6。 然后让这个整数与我字典中的一个字符名对齐。在

characters = {
'Stark': '1',
'Greyjoy': '2',
'California': '3',
'Whitewalkers': '4',
'Knights Watch': '5',
'Dalthraki': '6'
 }   

print 'Type 1 for Stark'
print 'Type 2 for Greyjoy'
print 'Type 3 for Lannister'
print 'Type 4 for Whitewalkers'
print 'Type 5 for Knights Watch'
print 'Type 6 for Dalthraki' 
choice = raw_input("> ")
if choice in characters:
    print 'You\'ve selected', choice 
else:
    splash()

我想让我的脚本打印“你已经选择斯塔克”后,让用户输入1。 谢谢你的帮助


Tags: 用户for字典type整数字符watchprint
3条回答

你真的不能那样用字典。您可以反转键/值对,然后使用字符[choice]来获取字符的名称。如果你想保持字典的原样,你最好的办法就是迭代这些项

characterName = None
names = characters.items()
while characterName is None and names:
    if names[0][1] == choice:
        characterName = names[0][0]
    else:
        names = names[1:]

运行此命令后,您将在characterName中有一个字符名,或者如果用户输入了无效的条目,则该名称将为None。在

把你的口述改成:

characters = {
'1':'Stark',
 '2':'Greyjoy',
'3':'California',
'4':'Whitewalkers',
'5':'Knights Watch',
'6':'Dalthraki'
 }  

并使用:

^{pr2}$

您将dict向后:

characters = {
'1': 'Stark',
'2': 'Greyjoy',
'3': 'California',
'4': 'Whitewalkers',
'5': 'Knights Watch',
'6': 'Dalthraki',
}   

print 'Type 1 for Stark'
print 'Type 2 for Greyjoy'
print 'Type 3 for Lannister'
print 'Type 4 for Whitewalkers'
print 'Type 5 for Knights Watch'
print 'Type 6 for Dalthraki' 
choice = raw_input("> ")
if choice in characters:
    print 'You\'ve selected', characters[choice] 
else:
    pass

相关问题 更多 >