Reputation: 41
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.
Upvotes: 0
Views: 60
Reputation: 91
Maybe you should use something like this
def lists_iteration(a,n):
for k in range(n):
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)
or just for loop from this function.
Upvotes: 2
Reputation: 78554
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
Upvotes: 2
Reputation: 3523
>>> a = [2, 4, 6, 8, 10]
>>> x = [(i-1,(i-1)*10,((i-1)*10)/3) for i in a]
>>> print x
[(1, 10, 3), (3, 30, 10), (5, 50, 16), (7, 70, 23), (9, 90, 30)]
>>>
>>> b = [i[0] for i in x ]
>>> print b
[1, 3, 5, 7, 9]
>>> c = [i[1] for i in x]
>>> print c
[10, 30, 50, 70, 90]
>>> d = [i[2] for i in x]
>>> print d
[3, 10, 16, 23, 30]
Upvotes: 0