在我的教科书中,我读到新手需要一些时间来识别这种结构:
choice = 'ham'
print ({
'spam': 1.25,
'ham': 1.99,
'eggs': 0.99,
'bacon': 1.10
}[choice])
结果:
The result is 1.99
说实话,我连一根绳子都抓不住,说什么解开。你能给我解释一下吗?
在我的教科书中,我读到新手需要一些时间来识别这种结构:
choice = 'ham'
print ({
'spam': 1.25,
'ham': 1.99,
'eggs': 0.99,
'bacon': 1.10
}[choice])
结果:
The result is 1.99
说实话,我连一根绳子都抓不住,说什么解开。你能给我解释一下吗?
它是一个 python 字典文字,结合使用choice
作为键的查找:
mapping = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99, 'bacon': 1.10}
choice = 'ham'
price = mapping[choice]
print(price)
如果选择不在字典中,您甚至可以将 .get 插入其中以返回一个值。
mapping = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99, 'bacon': 1.10}
choice = 'beans'
price = mapping.get(choice, 'not listed')
print(price)
将返回
not listed