pythonlistweb2py

Creating a loop for all variables with a similar name on python (web2py) gives me the values unsorted


Using this code:

form_vars = dict(request.vars)
torres = [v for k, v in form_vars.items() if k.startswith('torre_')]

I get a list with all the form's data that starts with "torre_", the problem starts with the fact that instead of creating a list like these:

#lets assume these are the values
 torre_1 = 1
 torre_2 = 2
 torre_3 = 3
 torre_4 = 4
# Instead of these
 torres = [1,2,3,4]
# I get these
 torres = [4,2,1,3]

I need these values for a mathematical formula that need the position of the value has a factor.

 Mp = 0
 cantTorres = len(torres)
    for i in range(1, cantTorres):
       Mp += ((torres[i]*cantTorres)*cantTorres)/cantTorres*i
       i = i+1

any suggestion?


Solution

  • If you get only the values in the list you loose the ordering info witch is in the keys of the dictionary.

    So you have to put the value together with the key in the list.

    form_vars = dict(request.vars)
    torres = [(k,v) for k,v in form_vars.items() if k.startswith('torre_'))
    

    Now torres has the form [(key1, value1), ... ]

    Now you can sort the list using the key.

    torres.sort(key=lambda x:x[0])
    

    and finally remove the keys.

    torre = [x[1] for x in torre]