Mun*_*mon 2 python dictionary python-3.x
我正在尝试根据值(foo)从字典中检索消息; 我面临的问题是每条消息都有多个索引.当索引改变值时,证明难以检索相同的消息.我知道这可能没有多大意义,但我希望通过查看它将有用的代码.
foo=int(input('What is foo'))#foo is always 1 to 10
bar={10:'10/10',
(8 or 9):'message1',
(6 or 7):'message2',
(4 or 5):'message3',
(2 or 3):'message4',
(0 or 1):'message5',
print(bar[foo])
Run Code Online (Sandbox Code Playgroud)
这段代码是一个更大的程序的一部分,它只是这个部分,我无法解决.Foo是预定的,因此用户不会在整个程序中输入它.我已经尝试了多个修复此问题,任何帮助将不胜感激.
例如,如果要使用单个整数作为键,可以使用math将每个键简化为单个唯一值
bar = {5:'10/10', # 10
4:'message1', # 9 or 8
3:'message2', # 7 or 6
2:'message3', # 5 or 4
1:'message4', # 3 or 2
0:'message5'} # 1 or 0
>>> foo = 7
>>> bar[foo // 2]
'message2'
Run Code Online (Sandbox Code Playgroud)