Double print on python loop

Using the code below, I can get the correct answer, however it repeats itself twice .

For example, I would like to get the result [1.2038, 1.206] , but the code below prints [1.2038, 1.206, 1.2038, 1.206] . Does anyone know what is wrong with my code? Any help would be greatly appreciated. Thank you

 spot = [1.2020, 1.2040] forwardSwap = [0.0018, 0.0020] forwardOutright = [] for i in range(len(spot)): for i in range(len(forwardSwap)): forwardOutright.append(spot[i] + forwardSwap[i]) print forwardOutright 
+5
source share
7 answers

You just need to flip once:

 spot = [1.2020, 1.2040] forwardSwap = [0.0018, 0.0020] forwardOutright = [] for i in range(len(spot)): forwardOutright.append(forwardSwap[i]+spot[i]) 

Outout:

 [1.2038, 1.206] 
+1
source

You should zip iterate over both lists instead of a nested loop at the same time:

 forwardOutright = [x+y for x, y in zip(spot, forwardSwap)] 
+21
source

This should work

 list(map(lambda i: sum(i), zip(spot, forwardSwap))) 
+4
source

According to this code in your question, both of your loops use a variable called i .

 for i in range(len(spot)): for i in range(len(forwardSwap)): 
+3
source

The problem you are having is that the inner loop executes completely every time the outer loop executes. ie for each element in spot , you look at each element in forwardSwap and add a new value to forwardOutright . Instead, you need to match one-to-one between the two lists so you can use:

for i,j in zip(spot, forwardSwap): forwardOutright.append(i+j)

You should also avoid obscuring your variables, i.e. using i in both loops, you can use i and j instead, for example. Otherwise, it will lead to unexpected actions of your program.

+3
source

Since you have nested for loops, the outer loop runs as many times as there are spot elements, and the inner loop runs as many times as the product of the lengths. You should use zip instead:

 for s, fs in zip(spot, forwardSwap): forwardOutright.append(s + fs) 

Or you can use list comprehension:

 forwardOutright = [s + fs for s, fs in zip(spot, forwardSwap)] 
+1
source

You have two nested loops that run twice.

Therefore, you execute the code in the second loop (2x2) 4 times.

0
source

Source: https://habr.com/ru/post/1273000/


All Articles