jeudi 23 août 2018

Python for loop with ifs

sorry for the newbie question! I have two dictionaries-- one with values and one with the index of the value.

d = {}
d['inds'] = [0, 5, 4, 2, 2, 5, 1]
d['vals'] = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

If I use the below loop:

for i in d['inds']:
    for v in d['vals']:
        for x in range(0, i):
         if i == x+1:
             print(v)
             break
    else:
         print(0)

I get the list of values 6 times so I tried swapping i and x

for i in d['inds']:
    for v in d['vals']:
        for x in range(0, i):
         if x == i+1:
             print(v)
             break
    else:
         print(0)

now I just get 0 listed 7 times.

but really I just want if the next iteration index = the last iteration index +1, to list the corresponding value if the next iteration index does not = the last iteration index +1, print 0 and keep going. so basically just filling in 0 when there is a missing index

Aucun commentaire:

Enregistrer un commentaire