I am facing problem while importing the output of a for-loop to another for loop.
My python script
JavaScript
x
17
17
1
import pandas as pd
2
import numpy as np
3
4
a=list(np.sort(np.random.uniform(low=2, high=3, size=(3,))))
5
a = [ round(elem, 1) for elem in a ]
6
#print(a)
7
8
for i,b in enumerate(a):
9
c=[b,b+1]
10
print(c)
11
12
for lrng in np.linspace(0,3,3):
13
d=[lrng, 15.0]
14
print(d[0])
15
e = {d[0]: c, d[1]:[2.0,2.0]}
16
print(e)
17
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.
JavaScript
1
13
13
1
current result
2
3
{0.0: [3.0, 4.0], 15.0: [2.0, 2.0]}
4
{1.5: [3.0, 4.0], 15.0: [2.0, 2.0]}
5
{3.0: [3.0, 4.0], 15.0: [2.0, 2.0]}
6
7
8
Expected result:
9
10
{0.0: [2.0, 3.0], 15.0: [2.0, 2.0]}
11
{1.5: [2.1, 3.1], 15.0: [2.0, 2.0]}
12
{3.0: [3.0, 4.0], 15.0: [2.0, 2.0]}
13
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
JavaScript
1
18
18
1
import pandas as pd
2
import numpy as np
3
4
a=list(np.sort(np.random.uniform(low=2, high=3, size=(3,))))
5
a = [ round(elem, 1) for elem in a ]
6
#print(a)
7
8
c = []
9
for i,b in enumerate(a):
10
c.append([b,b+1])
11
print(b, b+1)
12
13
for idx, lrng in enumerate(np.linspace(0,3,3)):
14
d=[lrng, 15.0]
15
print(d[0])
16
e = {d[0]: c[idx], d[1]:[2.0,2.0]}
17
print(e)
18