Skip to content Skip to sidebar Skip to footer

Use For Loop Inside Another For Loop

I'm trying to print a file in rainbow colors. But however I have a problem, here is my code: color = [91, 93, 92, 96, 94, 95] with open(sys.argv[1]) as f: for i in f.read(): f

Solution 1:

You don't want to loop over the colours for each letter just cycle through the colours, you can use itertools.cycle to cycle through the colors just calling next() to get the next color:

from itertools import cycle
color = cycle([91, 93, 92, 96, 94, 95])

withopen(sys.argv[1]) as f:
    for i in f.read():
       print('\033[{0}m{1}\033[{0};m'
             .format(next(color), i), end='', flush=True)

Solution 2:

You have to iterate them in a "zipping" way, possibly repeating the second one.

color = [91, 93, 92, 96, 94, 95]

with open(sys.argv[1]) as f:
    for i, c in itertools.izip(f.read(), itertools.cycle(color)):
        print('\033[{0}m{1}\033[{0};m'
          .format(c, i), end='', flush=True)

Solution 3:

As you mention you shouldn't use a second for loop.

You can use a color_index (initial value: 0), and you increment it (modulo the number of colors) at every loop, and use it: color[color_index].

Post a Comment for "Use For Loop Inside Another For Loop"