生成器表达式与列表推导 [英] Generator expressions vs. list comprehensions
问题描述
何时应使用生成器表达式,何时应使用Python中的列表推导?
When should you use generator expressions and when should you use list comprehensions in Python?
# Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
推荐答案
John的答案是很好的(列表理解是如果您想多次迭代某个对象,则效果更好).但是,还需要注意的是,如果要使用任何列表方法,都应使用列表.例如,以下代码将不起作用:
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work:
def gen():
return (something for something in get_some_stuff())
print gen()[:2] # generators don't support indexing or slicing
print [5,6] + gen() # generators can't be added to lists
基本上,如果您要做的只是迭代一次,则使用生成器表达式.如果要存储和使用生成的结果,则最好使用列表理解功能.
Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension.
由于性能是选择一个以上的最常见原因,所以我的建议是不要担心它,而只选择一个即可.如果您发现程序运行速度太慢,那么只有这样,您才应该回去担心调整代码.
Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
这篇关于生成器表达式与列表推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!