2

在我的教科书中,我读到新手需要一些时间来识别这种结构:

choice = 'ham'
print ({
    'spam': 1.25, 
    'ham': 1.99,
    'eggs': 0.99,
    'bacon': 1.10
}[choice])

结果:

The result is 1.99 

说实话,我连一根绳子都抓不住,说什么解开。你能给我解释一下吗?

4

2 回答 2

5

它是一个 python 字典文字,结合使用choice作为键的查找:

mapping = {'spam': 1.25, 'ham': 1.99, 'eggs': 0.99, 'bacon': 1.10}
choice = 'ham'
price = mapping[choice]
print(price)
于 2012-09-22T11:36:08.413 回答
3

如果选择不在字典中,您甚至可以将 .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
于 2012-09-22T12:23:38.360 回答