Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

importing for loop output to another for loop

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]}

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading