2

Need to sort HOST string array by its associated float speed

Is there nice way to get array from sorted tuples? Can I eliminate ordered array?

#!/usr/bin/env python

def getSpeed(url):
    if url == 'h1':
         return 0.522611856461
     elif url == 'h2':
         return 0.438368797302
     elif url == 'h3':
         return 0.443703174591

def orderHosts():
    hostInfo = []
    ordered = []
    hosts = ['h1', 'h2', 'h3']
    for host in hosts:
        hostInfo.append( (host, getSpeed(host)) )

    print hostInfo
    return ordered

if __name__ == "__main__":
    print("orderedHosts {}".format(orderHosts()))

output:

[('h1', 0.522611856461), ('h2', 0.438368797302), ('h3', 0.443703174591)]

orderedHosts []
4
  • Why do you have a function just to store values? Why not use a dictionary? What exacly are you trying to do? Commented Apr 17, 2016 at 23:12
  • function orderedHosts needs to return array of host ordered by getSpeed value. hostInfo could be a dictionary instead of array in which I am appending tuples, so append would become like hostInfo[speed] = host. I thought it would easier to sort tuples. Commented Apr 17, 2016 at 23:23
  • You misunderstood me. I was talking about the getSpeed function Commented Apr 17, 2016 at 23:25
  • In my actual software program (for Check Cashing) the little getSpeed function is an elaborate series of XML doc request, respose via Requests--would make your hair curl. I just need sort tips. Commented Apr 17, 2016 at 23:29

2 Answers 2

1

You can use the key parameter of sort or sorted to set a function that is called before sorting. In your case, sorted(hosts, key=getSpeed) should be enough.

Sign up to request clarification or add additional context in comments.

Comments

1

The sorted builtin function takes a key= argument. You can use that to provide a function that will return the comparison key (in this case, the speed) like so:

def getSpeed(host):
    ... as you had it
    return speed

hosts = ['h1', 'h2', 'h3']
ordered_hosts = sorted(hosts, key=getSpeed)

1 Comment

In my actual program the getSpeed function returns a Response object from Requests that is an XML doc with possible error status, etc. There is a Response.duration attribute but no simple function like getSpeed. I ment to try and ask about sorting array of tuples, converting tuples into array OR sorting dictionary, converting dictionary into array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.