我有一本字典,可能有也可能没有一个或两个键“foo”和“bar”。根据两者是否都有,我需要做不同的事情。以下是我正在做的事情(而且很管用):
foo = None
bar = None
if 'foo' in data:
if data['foo']:
foo = data['foo']
if 'bar' in data:
if data['bar']:
bar = data['bar']
if foo is not None and bar is not None:
dofoobar()
elif foo is not None:
dofoo()
elif bar is not None:
dobar()
这似乎太冗长了——在Python(2.7.10)中,使用什么惯用方法来实现这一点?在
您可以使用^{} 来缩短代码。不是在键不存在时引发
KeyError
,而是返回None
:以下是重构代码的另一种方法:
不过,我不确定这是否比克里斯蒂安的回答更清晰或更易读。在
为了好玩,您还可以使用
^{pr2}$dict
,布尔元组作为键,函数作为值:你应该这样使用它:
相关问题 更多 >
编程相关推荐