I want to sort a list that contains lists based on the sum of each inner list.
here's the current snippet I've got
vectors = []
for i in range(0, 10):
vectors.append(generate_vector()) # generate_vector() works, creates a list
for vector in vectors:
coin_list = findbest(vector) # findbest(vector) outputs a list
print coin_list, fitness(coin_list) # fitness(coin_list) gives the sum of coin_list
I want to sort vectors based on the results of fitness(coin_list) from low to high. What's the best way to do that?
Custom Sorting With key= The key function takes in 1 value and returns 1 value, and the returned "proxy" value is used for the comparisons within the sort. For example with a list of strings, specifying key=len (the built in len() function) sorts the strings by length, from shortest to longest.
There will be three distinct ways to sort the nested lists. The first is to use Bubble Sort, the second is to use the sort() method, and the third is to use the sorted() method.
@SilentGhost A comparison function is called on pairs of items and "should return a negative integer if self < other, zero if self == other, a positive integer if self > other." Whereas a key function is called once for each item and returns the value(s) you want an item sorted on.
You can use the key
param in sorted function
data = [[1,2,3], [14, 7], [5, 6, 1]]
print sorted(data, key=sum)
Output
[[1, 2, 3], [5, 6, 1], [14, 7]]
If you want to sort inplace
data = [[1,2,3], [14, 7], [5, 6, 1]]
data.sort(key=sum)
print data
Output
[[1, 2, 3], [5, 6, 1], [14, 7]]
Edit Just in case, if you are wondering how to sort in descending order, you can use reverse
parameter like this
data.sort(key=sum, reverse=True)
sorted(data, key=sum, reverse=True)
So, in your case
vectors = [generate_vector() for i in range(0, 10)]
print sorted([findbest(vector) for vector in vectors], key=sum)
Thats it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With