How do I reverse an itertools.chain object?

后端 未结 7 1038
佛祖请我去吃肉
佛祖请我去吃肉 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 16:14

    itertools.chain would need to implement __reversed__() (this would be best) or __len__() and __getitem__()

    Since it doesn't, and there's not even a way to access the internal sequences you'll need to expand the entire sequence to be able to reverse it.

    reversed(list(CHAIN_INSTANCE))
    

    It would be nice if chain would make __reversed__() available when all the sequences are reversable, but currently it does not do that. Perhaps you can write your own version of chain that does

提交回复
热议问题