更好的方法来做到这一点

时间:2014-03-19 10:23:47

标签: python python-2.7

我们如何以更好的方式处理此功能

我们如何才能提高效率

优化代码:

def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') is not None and tt.get('script') in ('abc','syz','mno')

2 个答案:

答案 0 :(得分:4)

tt.get('script') is not None部分是多余的,因为None也不在下一个元组中。

你的测试效率很高;如果第一个表达式已经是False,Python将不会评估第二个表达式。

def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')

演示:

>>> def is_interesting(tt):
...     return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')
... 
>>> is_interesting({'target_type': 42})
False
>>> is_interesting({'target_type': 670})
False
>>> is_interesting({'target_type': 670, 'script': ''})
False
>>> is_interesting({'target_type': 670, 'script': 'abc'})
True

答案 1 :(得分:1)

我的回答与Martijin完全相同。

def is_interesting(tt):
    return tt['target_type'] == 670 and tt.get('script') in ('abc','syz','mno')

我只是想回答这个问题:

  

"返回tt [' target_type'] == 670和tt.get('脚本')(' abc',' syz',& #39; mno')TypeError:' in'需要字符串作为左操作数"因此我添加了这个语句以应对tt.get的空值(' script')

示例:

>>> {'foo':'bar'}.get('notexist') in ('foo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not NoneType

>>> {'foo':'bar'}.get('notexist') in ('foo',)
False

>>> {'foo':'bar'}.get('notexist') in ['foo']
False

说明:第一个例子,()中只有一个元素,所以(&#39; foo&#39;)实际上会返回你的foo&#39; - 一个字符串;第二和第三可以确保你得到一个元组/列表。在括号内的单个元素后面放一个逗号是获取一个元素的方法。我想这就是你遇到的。

相关问题