I am facing problem while importing the output of a for-loop to another for loop.
My python script
import pandas as pd import numpy as np a=list(np.sort(np.random.uniform(low=2, high=3, size=(3,)))) a = [ round(elem, 1) for elem in a ] #print(a) for i,b in enumerate(a): c=[b,b+1] print(c) for lrng in np.linspace(0,3,3): d=[lrng, 15.0] print(d[0]) e = {d[0]: c, d[1]:[2.0,2.0]} print(e)
Actually facing problem in this line of code e = {d[0]: c, d[1]:[2.0,2.0]},
where value of c
should be different but by this script i am getting repeated value.
current result {0.0: [3.0, 4.0], 15.0: [2.0, 2.0]} {1.5: [3.0, 4.0], 15.0: [2.0, 2.0]} {3.0: [3.0, 4.0], 15.0: [2.0, 2.0]} Expected result: {0.0: [2.0, 3.0], 15.0: [2.0, 2.0]} {1.5: [2.1, 3.1], 15.0: [2.0, 2.0]} {3.0: [3.0, 4.0], 15.0: [2.0, 2.0]}
Advertisement
Answer
Your problem is that you keep over writting the value if c
which is why you only ever get the last value calculated in the next loop. You need to store the values in a list then read them back as needed.
Here I’ve created an empty list c = []
& then in the 3rd loop read out the values of c
as indexed by the counter idx
import pandas as pd import numpy as np a=list(np.sort(np.random.uniform(low=2, high=3, size=(3,)))) a = [ round(elem, 1) for elem in a ] #print(a) c = [] for i,b in enumerate(a): c.append([b,b+1]) print(b, b+1) for idx, lrng in enumerate(np.linspace(0,3,3)): d=[lrng, 15.0] print(d[0]) e = {d[0]: c[idx], d[1]:[2.0,2.0]} print(e)