Home > Software engineering >  subract 2nd value in one list with the first value of another list
subract 2nd value in one list with the first value of another list

Time:05-05

I have two lists A and B and I require the summation of the subtraction of the 2nd value in list B with the first value in list A. This process needs to happen iteratively until I reach the end of list A and both lists are of same length.

I have tried iterating through each list based on their range and after the subraction operation, increasing the iterator by one as below.

A = [700.0,05500.0,9470740.0,9467000.0,47077140.0,091600.0,480.0,940700.0,86640.0,947100.0,9201160.0,478800.0,472640.0,800.0]

B = [1300.0,15040.0,27040.0,947074260.0,7160.0,920.0,40.0,3220.0,9700.0,195460.0,2380.0,55400.0,20.0,279880.0]

new_list = []
for i in range(0,13):
    for j in range(0,13):
        new_list.append(listA[i 1] - listB[j])
        i  = 1
        j  = 1
new_list

But I get the error:

---->         new_list.append(listA[i 1] - listB[j])
IndexError: list index out of range

If I try with a smaller range it works but I need it to iterate through each value in the two lists. I need it to do listA(i) - listB(j 1) until the end.

CodePudding user response:

IIUC, you want:

pd.Series(A).shift(-1)-pd.Series(B)

output:

0          4200.0
1       9455700.0
2       9439960.0
3    -899997120.0
4         84440.0
5          -440.0
6        940660.0
7         83420.0
8        937400.0
9       9005700.0
10       476420.0
11       417240.0
12          780.0
13            NaN
dtype: float64

As list:

new_list = pd.Series(A).shift(-1).sub(pd.Series(B))[:-1].to_list()

output:

[4200.0, 9455700.0, 9439960.0, -899997120.0, 84440.0, -440.0, 940660.0, 83420.0, 937400.0, 9005700.0, 476420.0, 417240.0, 780.0]

CodePudding user response:

I made some changes, hope it works now:


listA = [700.0,05500.0,9470740.0,9467000.0,47077140.0,091600.0,480.0,940700.0,86640.0,947100.0,9201160.0,478800.0,472640.0,800.0]
listB = [1300.0,15040.0,27040.0,947074260.0,7160.0,920.0,40.0,3220.0,9700.0,195460.0,2380.0,55400.0,20.0,279880.0]

new_list = []
for i in range(0,len(listA)):
  for j in range(0,len(listB) - 1):
      new_list.append(listA[i] - listB[j   1])
      
print(new_list)

CodePudding user response:

Use zip:

sum((i-j for i,j in zip(a, b[2:])))

a,b are your lists

  • Related