Home > Blockchain >  Iterator to reverse a for loop's order of execution?
Iterator to reverse a for loop's order of execution?

Time:04-29

I have been searching the docs for itertools, as well as SO for a while now and have not yet found what I'm looking for. I'm hoping to reverse the order of execution of a for loop so the following happens:

for letter in ["A","B","C"]:
    do_something(letter)
    do_something_else(letter)


def do_something(letter):
   print("do_something with "   letter)
 
def do_something_else(letter):
   print("do something_else with "   letter)

with the normal output of a for loop being:

do_something with A
do something_else with A
do_something with B
do something_else with B
do_something with C
do something_else with C

And I would like it (the iterator) to output like:

do_something with A
do_something with B
do_something with C
do something_else with A
do something_else with B
do something_else with C

I won't lie it's been a long day so the answer is probably right under my nose, the best I've come up with so far is:

for letter in ["A","B","C"]:
    do_something(letter)

for letter in ["A","B","C"]:
    do_something_else(letter)


def do_something(letter):
   print("do_something with "   letter)
 
def do_something_else(letter):
   print("do something_else with "   letter)

But that feels very clunky since I'm repeating the for loop. Any help is vastly appreciated. Thanks all!

CodePudding user response:

Do the iteration twice:

for letter in ["A","B","C"]:
    do_something(letter)

for letter in ["A","B","C"]:
    do_something_else(letter)

CodePudding user response:

Another option is an outer loop over the functions, and an inner loop over the letters.

for f in [do_something, do_something_else]:
    for letter in ["A","B","C"]:
        f(letter)

Yet, another alternative is to use itertools/product on the functions an inputs (output is as desired).

from itertools import product

for f, letter in product([do_something, do_something_else], ["A","B","C"]):
    f(letter)

CodePudding user response:

How about

results = [list(map(func,letters)) for func in [do_something,do_something_else]]

CodePudding user response:

You could use the itertools.tee() function to make two independent letter iterators and the built-in zip() function to "weave" the functions and letters together like so:

from itertools import tee


def do_something(letter):
   print("do_something with "   letter)

def do_something_else(letter):
   print("do something_else with "   letter)

for function, letters in zip((do_something, do_something_else), tee(["A","B","C"]) ):
    for letter in letters:
        function(letter)

  • Related