Stagg Stagg - 6 months ago 15
Python Question

Apply formula with two different lists

I have two lists like this:

listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]


I have to apply this formula in the lists:

n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2


The 'n' is the elements of listA, 'x' is the elements that correspond to the same index of 'n' in listB.

I need to apply this formula to all the elements in both list. So that when the loop runs the first time it needs to do this:

51/pi*((1*0.1)+1)**2 - pi *(1*0.1)**2


For the second this, it needs to do this:

988/pi*((2*0.1)+1)**2 - pi*(2*0.1)**2


And it repeats until the end of both lists.

I know I have to use a 'for' loop, but my problem is that I don't know how to get the elements from the second list. I'm trying to do this:

for n in listA:
n/pi*((......))


Inside thhe brackets it should be the elements from listB but I don't know how to get them, and they need to have the same index as the element from listA.
The output should be a third list with the result of each formula applied.

I have tried to explained myself the best way possible, but if you don't understand my question feel free to ask any question.

Thanks in advance.

Answer

I assume both lists have the same size all the time, most pythonic way is to use lambda and list comprehensions:

listA = [51, 988, 1336, 2067, 1857, 3160]
listB = [1, 2, 3, 4, 5, 6]

from math import pi

formula = lambda n,x: n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2

res = [ formula(a,b) for a,b in zip(listA,listB) ]

>> [19.621466242038217,
 452.96994140127384,
 718.7747248407644,
 1289.7268993630569,
 1329.8678662420382,
 2575.175332484077]
Comments