为什么`heapq.merge(some_lists_of_iterators)`不返回迭代器的迭代器?

时间:2016-05-25 19:15:53

标签: python python-2.7 iterator heap generator

在以下代码中:

import heapq

nums = [1,2,3]
result = [set([])]
bases = []

for n in nums:
    bases.append(set([n]))       # Now bases is [set([1]), set([2]), set([3])]

def gen (base):
    for r in result:
        if base != r:
            yield base | r       # It yields set([]) unions base

itr1 = iter(map(gen, bases))
itr2 = heapq.merge(*map(gen, bases))

为什么itr1是迭代器的迭代器,但是itr2是集合的迭代器?如下所示:

for i in itr1:
    print i                      #<generator object gen at 0x1028adcd0> 
                                 #<generator object gen at 0x1028add20> 
                                 #<generator object gen at 0x1028d5730>

for i in itr2:
    print i,                     #set([3]) set([2]) set([1])

1 个答案:

答案 0 :(得分:0)

您是否尝试过更改:

itr1 = iter(map(gen, bases))
itr2 = heapq.merge(*map(gen, bases))

为:

itr1 = iter(map(gen, bases))
itr2 = iter(heapq.merge(*map(gen, bases)))