heapq.merge:merge后merge的结果,原来的merge为空
首先我创建了 a & 的两个结果; b 使用heapq.merge,但是在合并a&b之后,我发现a的列表是空的。
>>> a=merge([1,2],[3,4])
>>> b=merge([4,5],[6,7])
>>> list(a)
[1, 2, 3, 4]
>>> merge(a,b)
<generator object merge at 0x365c370>
>>> list(a)
[]
>>>
list(a)
最终结果为空,为什么merge(a,b)
会改变a?
First I created two results of a & b by using heapq.merge
, but after merge
ing a&b, I found the list of a is empty.
>>> a=merge([1,2],[3,4])
>>> b=merge([4,5],[6,7])
>>> list(a)
[1, 2, 3, 4]
>>> merge(a,b)
<generator object merge at 0x365c370>
>>> list(a)
[]
>>>
The final result of list(a)
is empty, why does merge(a,b)
change a?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如文档(以及示例中
merge(a,b)
的输出)所示,merge
的结果是一个迭代器。迭代器只能使用一次,您无法重置或倒回它们,即使可以,您的代码也不会执行此操作。 (当然,对于给定的集合,您可以有多个独立的迭代器,至少如果该集合支持的话)。前两个
merge
调用返回生成器,第三个调用消耗这些生成器,因此a
和b
随后被耗尽。 (实际上,list(a)
首先消耗a
,因此在该代码段中merge(a, b)
只会看到a
的项目>b,但想法是相同的。)这并不意味着,如果你传递一个列表,它不会改变。但使用迭代器意味着改变它。As the documentation (and the output on
merge(a,b)
in your example) indicates, the result ofmerge
is an iterator. Iterators can only be consumed once, you can't reset or rewind them, and even if you could, your code doesn't do it. (Of course you can have several independent iterators for a given collection, at least if the collection supports it).The first two
merge
calls return generators, the third call consumes those generators, and hencea
andb
are exhausted afterwards. (Actually,list(a)
consumesa
first, so in that snippetmerge(a, b)
will only see the items ofb
, but the idea is the same.) It doesn't mean to, and if you pass e.g. a list it won't be changed. But consuming an iterator means mutating it.您的
a
不是列表,而是迭代器。如果使用一次,则无法进行第二次迭代。这与merge
无关;你在这里看到同样的效果:Your
a
is not a list but an iterator. If you use it once, you cannot iterate with it a second time. This has nothing to do withmerge
; you see the same effect here:heapq.merge 的返回值是一个迭代器。当您将
list
应用于迭代器时,它就会被消耗。迭代器适合一次遍历一组值。所以第二次调用list(a)
时,结果为空。The return value of
heapq.merge
is an iterator. When you applylist
to an iterator, it is consumed. An iterator is good for one pass over the set of values. So the second timelist(a)
is called, the result is empty.