Python Forum

Full Version: How to define a function to create a resorted list?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
After day-long trial-and-error and research I found the code from web which does what I tried to do, i.e. resorting a list according to absolute difference to a value.

def sortleastdev(a, val): 
    b =[[0 for x in range(2)] for y in range(len(a))] 
    for i in range(0, len(a)):  
        b[i][0] = abs(a[i]-val)  
        b[i][1] = i 
    b.sort()  
    for i in range(0, len(a)):  
        print(a[b[i][1]])
     
a = [7, 12, 2, 4, 8, 0] 
val = 6
sortleastdev(a, val)  

from statistics import mean
L = [1.238623532,1.315924461,1.430787909,0.65436604,0.78646411,1.551692625,1.143410924,1.044302349,1.12971696,1.007285185,1.009553518,0.646888596,1.027950548,0.950471257,1.048221271,1.070840989]
sortleastdev(L, mean(L))
But what if I wish to define "sortleastdev" as a new list? How to make it giving me a new resorted list instead, where "sortleastdev(L, mean(L))[0]" would be 1.070840989?
I'm sure it's a very newbie question. I tried to search through the web without progress though. Much appreciated.
You only need to return the list instead of printing it
def sortleastdev(a, val): 
    b =[[0 for x in range(2)] for y in range(len(a))] 
    for i in range(0, len(a)):  
        b[i][0] = abs(a[i]-val)  
        b[i][1] = i 
    b.sort()
    return [a[b[i][1]] for i in range(len(a))]

...
result = sortedleastdev(L, mean(L))
Functions that return values are much more useful than functions that print values.
Thanks a lot for the help, I feel progress!
Why not use a sorting key?
(Aug-07-2020, 05:13 PM)deanhystad Wrote: [ -> ]Why not use a sorting key?

How does that work? Further info would be appreciated.
Look up sorting keys in the python documentation. They even provide examples. I wrote a 3 line script to sort you list by deviation from the mean. Used the standard sorted() call and used the key to convert values in the list to a deviation value.

https://docs.python.org/3/howto/sorting.html
(Aug-07-2020, 05:26 PM)deanhystad Wrote: [ -> ]Look up sorting keys in the python documentation. They even provide examples. I wrote a 3 line script to sort you list by deviation from the mean. Used the standard sorted() call and used the key to convert values in the list to a deviation value.

https://docs.python.org/3/howto/sorting.html

Great to learn about that. It does simplify a lot! Thanks very much.