How do I reverse an itertools.chain object?

后端 未结 7 1063
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-14 16:01

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 fo         


        
7条回答
  •  遇见更好的自我
    2021-02-14 16:25

    if num < 0:
        lst = list(chained)
        lst.reverse()
        return lst
    else:
        return chained
    

    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).

    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.

提交回复
热议问题