Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - sort lists based on their sum

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?

like image 704
user2733911 Avatar asked Nov 09 '13 05:11

user2733911


People also ask

How do you sort a list in custom order in Python?

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.

How a nested list is sorted?

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.

How do you sort a complex list in Python?

@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.


1 Answers

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.

like image 88
thefourtheye Avatar answered Sep 26 '22 19:09

thefourtheye