Home > other >  How to loop over stacks of lists being multiplied in chunks
How to loop over stacks of lists being multiplied in chunks

Time:01-19

I have multiple lists such as x1, x2 and x3, each containing 10 list elements (numbers). Then I have two other lists, namely c_a and c_b, which are of equal length e.g. containing 3 elements. I wanted to multiply elements of lists x1, x2 and x3 in chunks with those in c_a and c_b as shown below;

    x_1[0:3]=[i*c_a[0]**2 for i in x_1[0:3]]
    x_1[3:6]=[i*c_b[0]**2 for i in x_1[3:6]]
    x_1[6:10]=[i*c_a[0]*c_b[0] for i in x_1[6:10]]

I now desire to embed this multiplication in a loop such that the names of x1, x2 and x3 and index of c_a[index] and c_b[index] change iteratively. I look forward to your suggestions. Thanks in advance!

CodePudding user response:

Put all the lists in another list. Then use zip() to loop over this list along with the lists c_a, c_b, and c_b_Ni.

for l, a, Ni, b in zip([x1, x2, x3], c_a, c_b_Ni, c_b):
    l[0:3]=[i*a**2 for i in l[0:3]]
    l[3:6]=[i*Ni**2 for i in l[3:6]]
    l[6:10]=[i*a*b for i in l[6:10]]
  •  Tags:  
  • Related