Soros Soros - 2 months ago 12
Python Question

How to iterate over multiple related lists until specified number times in python?

I want to iterate to Nth times my list. This is my example code.

a = [2, 4, 6, 8, 10]
b = [i - 1 for i in a]
print(b)
c = [i * 10 for i in b]
print(c)
d = [i / 3 for i in c]
print(d)
a = [m/n for m,n in zip(d,a)]
print(a)
b=[i - 1 for i in a]
print(b)
c = [i * 10 for i in b]
print(c)
d = [i / 3 for i in c]
print(d)
a = [m/n for m,n in zip(d,a)]
print(a)


For example, I want to do iteration 10 times over all the lists. But I don't want to write those same codes 10 times. Is there efficient way to get my desired results? Thanks in advance.

Answer Source

If you don't actually need the intermediate lists, you can combine all the maths ops into one:

def func(a, n):
   for _ in range(n):
      a = [(i-1)*10/(3*i) for i in a]
   return a