Sara
Sara

Reputation: 163

performing multiple for loops in python automatically and simultaneously

I have a challenging questions: Imagine that I have a list of strings with the same length like the following 'seq' list:

seq=['FFFSS', 'FFEEE', 'WWQQA', 'PPRSA', 'MMMMM', 'PPEEE','HMSII','KKKDD','WTYUI','OPOPO','YYYYY', 'QQERT','YYRER', 'NNBBB', 'CCXZZ', 'UIOOP', 'QQWEE', ….,'FFGEE']

But Of course my real 'seq' list has so many more strings (at least 100 strings all having the same length).

If I want to open string number 0 upto string number 3 simultaneously, I need to write a multiple 'for loop' like the following:

n= 0
for a0, a1, a2 in zip(seq[n+0], seq[n+1], seq[n+2]):   print(a0, a1, a2)

Now if I want to extend the above 'for loop' and open string number 0 upto string number 5 simultenously, I need to change the above code like the following:

n= 0
for a0, a1, a2, a3, a4 in zip(seq[n+0], seq[n+1], seq[n+2], seq[n+3], seq[n+4]):   print(a0, a1, a2, a4)

The output for the above code is as following which is my favorite output:

F F W P
F F W P
F E Q R
S E Q S
S E A A

Finally imagine that I want to extend above code more and more and for example open string number 0 upto string number 100 simultaneously, so of course I can't extend the code manually and I need to find a way to extend the above multiple 'for loop' automatically. Imagine that I need the final multiple loop as the following:

n= 0
for a0, a1, a2, a3, a4, …, a100  in zip(seq[n+0], seq[n+1], seq[n+2], seq[n+3], seq[n+4], …, seq[n+100]):   print(a0, a1, a2, a4, …, a100)

My question is that if I want to have these 100 'a' variables, is there any way to make multiple 'for loop' automatically for a huge number of variables simultaneously?

Upvotes: 1

Views: 270

Answers (2)

Bubble Bubble Bubble Gut
Bubble Bubble Bubble Gut

Reputation: 3358

To create seq[n+0], seq[n+1], ..., seq[n+100], use itemgetter:

from operator import itemgetter

seqs = [itemgetter(n+i)(seq) for i in range(101)]

for a in zip(*seqs):
    # do something with a[0], a[1], a[2] .....

Upvotes: 3

bla
bla

Reputation: 1870

You may zip everything together with zip(*a).

>>> l = ['abc', 'cba', 'xyz']
>>> for a in zip(*l):
...     print(a)
... 
('a', 'c', 'x')
('b', 'b', 'y')
('c', 'a', 'z')

You may then do anything you want with a. For example:

>>> l = ['abc', 'cba', 'xyz']
>>> for a in zip(*l):
...     print(a[0] + a[2])
... 
ax
by
cz

Upvotes: 2

Related Questions