Home > Software engineering >  Python combine 2 un nested for loops to get result
Python combine 2 un nested for loops to get result

Time:09-30

Why is my code below not working correctly? The answer for d3 is getting calculated incorrectly. I want d3 to be [-1,1,3] but instead I am getting [1,2,3]. How can I fix this code?

x = [1,2,3]
z = 3 
y = [4,5,6]
d =[]
for i in range(3):
    d1 = x[i]-z # [-2,-1,0]
for j in range(3):
    d2 = y[j]-z # [1,2,3]
    d3 = d1 d2 # [-1,1,3]
    d.append(d3)
for i in d :
    print (i)

CodePudding user response:

There doesn't seem to be a need for the second 'for' loop. This achieves what I think you are looking for:

x = [1,2,3]
z = 3 
y = [4,5,6]
d =[]
for i in range(3):
    d1 = x[i]-z # [-2,-1,0]
    d2 = y[i]-z # [1,2,3]
    d3 = d1 d2 # [-1,1,3]
    d.append(d3)
for i in d :
    print (i)

When you start a second 'for' loop to iterate indexes of 'y', you are only going to get the last index of 'for' loop iterating over 'x'.

CodePudding user response:

This can be done using one list comprehension:

x = [1,2,3]
z = 3 
y = [4,5,6]

d = [a   b - z*2 for a, b in zip(x, y)]

Or for a numpy approach (which is overboard but what the heck)

import numpy as np

x = np.array([1,2,3])
z = 3 
y = np.array([4,5,6])

d = x   y - z*2

CodePudding user response:

I couldn't understand the context, but if you want d3 to be [-1,1,3]. You need to place both d1 and d2 within the same loop.

x = [1,2,3]
z = 3 
y = [4,5,6]
d =[]
for i in range(3):
    d1 = x[i]-z # [-2,-1,0]
    d2 = y[i]-z # [1,2,3]
    d3 = d1 d2 # [-1,1,3]
    d.append(d3)
for i in d :
    print (i)

CodePudding user response:

Looking at what you have commented in your question as to what the lists look like, I think this is what you require:

x = [1,2,3]
z = 3 
y = [4,5,6]
d1 = [(e - z) for e in x]   # [-2,-1,0]
d2 = [(e - z) for e in y]   # [1,2,3]
d3 = [ a   b for a, b in zip(d1, d2)]  # [-1,1,3]

for i in d3:
    print(i)

Output:

-1
1
3

CodePudding user response:

You must iterate over a list and get the sum you want:

x = [1,2,3]
z = 3 
y = [4,5,6]
d =[]
d1 = []
d2 = []
for i in range(3):
    x1 = x[i]-z # [-2,-1,0]
    d1.append(x1)
for j in range(3):
    y1 = y[j]-z # [1,2,3]
    d2.append(y1)
    
for k in range(3):
    d3 = d1[k]   d2[k]
    d.append(d3)
for i in range(3):
    print(d[i])  
  • Related