Python:解释器是否优化任何语句([隐式循环])?

问题描述 投票:0回答:1

我想知道python解释器会自动完成哪种类型的优化。例如。我有以下代码来检查字符串是否以startList中的任何子字符串开头:

def startswithAny(string, startList):
    return any([string.startswith(x) for x in startList])

假设startList包含1000个条目,但是string.startswith(startList[0])已经产生true。会发生什么? [string.startswith(x) for x in startList]是否仍将得到充分评估?还是解释器会认识到any()已经产生true?

如果不是,比恕我直言,编写像这样的非pythonic代码更有意义,如下所示:

def startswithAny(string, startList):
    for x in startList:
        if string.startswith(x): 
            return True
    return False

谢谢

python optimization
1个回答
0
投票

any功能是保证短路,这意味着当它找到True元素时就终止。 any()代码基本上等同于以下内容:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

您可以看到元素为True的那一刻,循环就停止了。

所以是的,您在末尾编写的代码本质上等效于在其上运行any()any()是更pythonic的方式。

© www.soinside.com 2019 - 2024. All rights reserved.