如果我这样做,每次迭代都会调用 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/