哪个在python中更好?

aru*_*lmr 3 python conditional-statements

我在python中使用了一些条件语句,它们给出了相同的结果.我想知道哪个更好,它们之间的性能和逻辑有什么不同.

情况1:

if a and b and c:
    #some action
Run Code Online (Sandbox Code Playgroud)

VS

if all( (a, b, c) ):
    #some action
Run Code Online (Sandbox Code Playgroud)

案例2:

if a or b or c:
    #some action
Run Code Online (Sandbox Code Playgroud)

VS

if any( (a, b, c) ):
    #some action
Run Code Online (Sandbox Code Playgroud)

案例3:

if not x in a:
    #some action
Run Code Online (Sandbox Code Playgroud)

VS

if x not in a:
    #some action
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我想知道性能和逻辑的差异以及首选方式.

Tim*_*Tim 6

情况1

来自https://docs.python.org/2/library/functions.html#all

所有(迭代器)

如果iterable的所有元素都为true(或者iterable为空),则返回True.相当于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
Run Code Online (Sandbox Code Playgroud)

这意味着,if a and b and c:if all( (a, b, c) ):做同样的事情(废话),但all()涉及的函数调用和循环,所以它必然是慢一点,但说真的,只是一点点.

if a and b and c:如果你只有几个变量(不超过3个)来保持它的可读性,all()如果你有更多,我会说你使用.

请记住:可读性几乎总是比轻微的性能提升更重要.

all()并且any()可以将列表理解作为输入,这是非常有用的.

注意:all()仅适用于Python 2.5+


案例2

与案例1相同,真的.因为它几乎完全相同的功能

任何(迭代器)

如果iterable的任何元素为true,则返回True.如果iterable为空,则返回False.相当于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
Run Code Online (Sandbox Code Playgroud)

注意:any()仅适用于Python 2.5+


案例3

来自http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations

使用不是运营商而不是......是.虽然两个表达式在功能上是相同的,但前者更具可读性和首选性.

您应该使用if x not in a:if not x in a:,因为风格指南是圣洁