How do I reverse an itertools.chain object?

后端 未结 7 1061
佛祖请我去吃肉
佛祖请我去吃肉 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:17

    reversed only works on objects that support len and indexing. You have to first generate all results of a generator before wrapping reversed around them.

    However, you could easily do this:

    def bar(num):
        import itertools
        some_sequence = (x*1.5 for x in range(num, -1, -1))
        some_other_sequence = (x*2.6 for x in range(num, -1, -1))
        chained = itertools.chain(some_other_sequence, some_sequence)
        return chained
    

提交回复
热议问题