生成器与列表理解

生成器与列表理解

本文介绍了生成器与列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些东西,当以列表理解运行时,运行正常.

I have something, when run as a list comprehension, runs fine.

看起来

[myClass().Function(things) for things in biggerThing]

Function是一种方法,它会建立一个列表.该方法本身不返回任何内容,但可以在其中操作列表.

Function is a method, and it builds a list. The method itself doesn't return anything, but lists get manipulated within.

现在,当我将其更改为发电机

Now when I change it to a generator ,

(myClass().Function(things) for things in biggerThing)

它不会像我期望的那样处理数据.实际上,它似乎根本没有操纵它.

It doesn't manipulate the data like I would expect it to. In fact, it doesn't seem to manipulate it at all.

列表理解生成器之间的功能区别是什么?

What is the functional difference between a list comprehension and a generator?

推荐答案

对生成器进行消耗时会对其进行动态评估.因此,如果您从未迭代生成器,则永远不会评估其元素.

Generators are evaluated on the fly, as they are consumed. So if you never iterate over a generator, its elements are never evaluated.

因此,如果您这样做:

for _ in (myClass().Function(things) for things in biggerThing):
    pass

Function将运行.

现在,您的意图真的在这里还不清楚.

Now, your intent really isn't clear here.

相反,请考虑使用map:

map(myClass().Function, biggerThing)

请注意,这将始终使用MyClass的相同实例

Note that this will always use the same instance of MyClass

如果有问题,请执行以下操作:

If that's a problem, then do:

for things in BiggerThing:
    myClass().Function(things)

这篇关于生成器与列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:16