在Python中哪个更好?

3

我在Python中使用了一些条件语句,它们给出了相同的结果。我想知道哪个更好,并且它们之间在性能和逻辑方面有什么区别。

情况1:

if a and b and c:
    #some action

vs

if all( (a, b, c) ):
    #some action

案例2:
if a or b or c:
    #some action

vs

if any( (a, b, c) ):
    #some action

案例三:
if not x in a:
    #some action

vs

if x not in a:
    #some action

在上述情况中,我想了解性能和逻辑方面的差异以及首选方式。

区别在哪里?速度、逻辑、可读性等方面吗? - user1907906
@Tichodromamuraria 修改了问题。 - arulmr
1个回答

6
案例1

https://docs.python.org/2/library/functions.html#all获取信息。

该函数返回一个布尔值,表示给定可迭代对象中的所有元素都为True,否则返回False。如果可迭代对象为空,则返回True。

all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True
这意味着 if a and b and c:if all((a, b, c)): 做的是相同的事情,但是 all() 包含函数调用和循环,因此它会稍微慢一点,但实际上只是一点点。

如果你只有几个变量(不超过3个),我建议你使用 if a and b and c: 使其易读,如果你有更多变量,则使用 all()

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

all()any() 可以接受列表推导式作为输入,这非常有用。

注意:仅 Python 2.5+ 支持 all()


案例 2

与案例1几乎相同,因为它们是几乎完全相同的函数。

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False
注意:`any()` 只在 Python 2.5+ 版本可用。
案例3 引自 http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations

使用 `is not` 操作符而不是 `not ... is`。虽然两个表达式的功能相同,但前者更易读且更受青睐。

应该使用 `if x not in a:` 而不是 `if not x in a:`,因为风格指南是神圣的。

我想补充一点,在前两种情况下,如果我们已经有一个可迭代对象,我们应该使用anyall,因为如果我们有单独的元素,则将它们转换为可迭代对象将会增加额外的成本。 - Ankur Ankan
@AnkurAnkan 是的,我想我意思是说它可以将LC作为输入 :-) - Tim
这回答了我的问题。谢谢。 - arulmr
1
@TimCastelijns,我喜欢你的说法“因为样式指南是神圣的”。但是我的父亲告诉过我一个规则,可以简化(相当复杂的)捷克语法 - 尝试所有首先想到的选项,并选择听起来最自然的那个。这意味着您是母语使用者,所以唯一要做的就是努力成为本地的Python使用者。 - Jan Vlcinsky
@JanVlcinsky 唯一需要做的就是努力成为Python本地说话者 我正在努力学习;-)与此同时,我只是喜欢遵循官方的样式指南 :-) - Tim
@TimCastelijns 我们应该把风格指南看作是我们母语的表达方式 :-). - Jan Vlcinsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接