python - Python 中的 'in' 运算符是 "lazy"吗?

标签 python python-3.x

如果我这样做,每次迭代都会调用 split() 吗?:

a = [word for word in post.split() if len(word) > 10]

我应该这样做以获得更好的性能吗?

s = post.split()
a = [word for word in s if len(word) > 10]

最佳答案

post.split() 只被调用一次。您可以通过将 post.split() 替换为每次调用时打印的函数来验证它:

>>> post = 'a b c d'
>>> def split_post():
...     print('split_post is called')
...     return post.split()
... 
>>> a = [word for word in split_post() if len(word) > 10]
split_post is called

您不需要为了性能而将表达式分成两个语句。

关于python - Python 中的 'in' 运算符是 "lazy"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42463633/

相关文章:

python - 使用 Python 计算持续时间/ session 的时间

python - 十六进制转pem文件

python - 使用循环更改二维列表中的多个值

python-3.x - 使用cuda进行多处理

python - 在IPython中运行ProcessPoolExecutor

python & c-c++扩展模块案例段错误

Python 3 Selenium 键错误 : 'value' Issue won't initialize Geckodriver for Firefox

python - 如何在Pythonista iOS中运行Flask?

python - 无法在python中找到质数代码中的错误

python - 从计算中排除列,然后再次检索它