问题描述
我的函数创建了一系列的生成器:
My function creates a chain of generators:
def bar(num):
import itertools
some_sequence = (x*1.5 for x in range(num))
some_other_sequence = (x*2.6 for x in range(num))
chained = itertools.chain(some_sequence, some_other_sequence)
return chained
我的函数有时需要以相反的顺序返回chained
.从概念上讲,以下是我想做的事情:
My function sometimes needs to return chained
in reversed order. Conceptually, the following is what I would like to be able to do:
if num < 0:
return reversed(chained)
return chained
不幸的是:
>>> reversed(chained)
TypeError: argument to reversed() must be a sequence
我有什么选择?
这是一些实时图形渲染代码,因此我不想使其变得太复杂/太慢.
This is in some realtime graphic rendering code so I don't want to make it too complicated/slow.
编辑:当我第一次提出这个问题时,我还没有想到发电机的可逆性.正如许多人指出的那样,生成器是不可逆的.
EDIT:When I first posed this question I hadn't thought about the reversibility of generators. As many have pointed out, generators can't be reversed.
事实上,我确实想颠倒链中扁平化的内容;不只是生成器的顺序.
I do in fact want to reverse the flattened contents of the chain; not just the order of the generators.
基于响应,我没有一个可用于反转itertools.chain的调用,因此,我认为这里唯一的解决方案是使用列表,至少对于反转情况,也许对两者都使用. >
Based on the responses, there is no single call I can use to reverse an itertools.chain, so I think the only solution here is to use a list, at least for the reverse case, and perhaps for both.
推荐答案
if num < 0:
lst = list(chained)
lst.reverse()
return lst
else:
return chained
reversed()
需要一个实际的序列,因为它会按索引向后迭代,这对于生成器(仅具有"next"项的概念)不起作用.
reversed()
needs an actual sequence, because it iterates it backwards by index, and that wouldn't work for a generator (which only has the notion of "next" item).
由于无论如何都需要展开整个生成器以进行反转,所以最有效的方法是将其读取到列表中,并使用.reverse()
方法就地反转该列表.
Since you will need to unroll the whole generator anyway for reversing, the most efficient way is to read it to a list and reverse the list in-place with the .reverse()
method.
这篇关于如何反转itertools.chain对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!