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, 1
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.
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 sorted(fitness(coin_list), key=sum)