For simple list creations, it is recommended to use list comprehension. However, when it comes to more complicated scenarios, spanning the list creation across multiple lines is more advisable.
e.g. for a simple task
[x for x in range(10)]
Run Code Online (Sandbox Code Playgroud)
e.g. for a more complicated task
result = []
for x in complicated:
if y is complex:
for z in intricate_stuff:
result.append(convoluted(z))
Run Code Online (Sandbox Code Playgroud)
(I probably would still use a multi-line list comprehension for the above example, but anyways you get the idea.)
Recently, I found myself achieve list creation like that using a generator like:
def gen():
for x in complicated:
if y is complex:
for z in intricate_stuff:
yield convoluted(z)
result = [x for x in gen()]
Run Code Online (Sandbox Code Playgroud)
It's more natural for me to use a generator like this to create a list (well, generate a list), but I feel it might add unnecessary complexity.
Is this recommended? or, which way is more pythonic?
生成器一次一个地构建元素。所以对于这样的陈述:
for e in my_generator():
pass
Run Code Online (Sandbox Code Playgroud)
每次迭代时都会生成变量的值,不存储上一次迭代时e的值。e因此它不存储列表的整个元素。所以它的内存效率很高。
但是,如果您计划在列表理解中使用生成器,则使用生成器是没有意义的,因为需要生成和存储所有元素。
在这种情况下,您可以使用如下所示的列表理解:
result = [ convoluted(z) for x in complicated if y is complex for z in intricate_stuff ]
Run Code Online (Sandbox Code Playgroud)