#!/usr/bin/python # comparison function for use by list.sort to sort elements based on the second # element of the tuples # first and second should be two element tuples with an integer weight being # the second element of each def rev_weighted_tuple_cmp(first, second): # if first tuple is greater than the second if first[1] > second[1]: return -1 # if the tuples are equal elif first[1] == second[1]: return 0 # if the first tuple is less than the second else: return 1 # function to return a list from a list of weighted tuples # list_of_tuples should be a list of two element tuples of which the second # element is an integer weight # returns a list of elements which are the first elements of each tuple. the # list is sorted in descending order based on the weighting def weighted_list(list_of_tuples): # sort the list of tuples based on the weight list_of_tuples.sort(rev_weighted_tuple_cmp) # build the return list of just the first elements # initialize the list with first element ret_list = [list_of_tuples[0][0]] # start the index at one since we already added the first element index = 1 # add the remaining elements while index < len(list_of_tuples): ret_list.append(list_of_tuples[index][0]) index = index+1 # return the list return ret_list # test tuples a = ('test1.fedoraproject.org',30) b = ('test2.fedoraproject.org',5) c = ('test3.fedoraproject.org',45) d = ('test4.fedoraproject.org',10) # test list of tuples l = [a,b,c,d,a,b,c,d] print l # create new list new_list = weighted_list(l) print new_list