从函数返回的集合中进行迭代的最有效方法是什么?

我最近开始使用迭代器,并且对于解决以下问题的正确方法(或根本就不是问题的方法)尚不确定。

Let's say I have an input_set that is rather large, I want to generate an intermediary_set (or whatever iterable), that will be even larger. However, the latter will only be used once in a for loop later in the code. So, I thought I should make a generator function that would take the input_set as parameter, apply the appropriate operations to obtain intermediary_set, and loop over it with a yield statement.

例如:

def make_a_generator(input_set):
    intermediary_set = some_operations(input_set)
    for i in intermediary_set:
        yield i

One issue is that some_operations() involve some set operations, so that it is not possible to make a generator directly from looping over the input_set.

另外,我认为我可以做到:

iterator = (i for i in some_operations(input_set))

But I wonder if there is a better way, or another more efficient if intermediary_set is very large.

评论