Python-根据列表的总和对列表进行排序 [英] Python - sort lists based on their sum

查看:82
本文介绍了Python-根据列表的总和对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于每个内部列表的总和对包含列表的列表进行排序.

I want to sort a list that contains lists based on the sum of each inner list.

这是我当前的摘要

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

我想根据适应度(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?

推荐答案

您可以在排序函数中使用key参数

You can use the key param in sorted function

data = [[1,2,3], [14, 7], [5, 6, 1]]
print sorted(data, key=sum)

输出

[[1, 2, 3], [5, 6, 1], [14, 7]]

如果您想就位排序

data = [[1,2,3], [14, 7], [5, 6, 1]]
data.sort(key=sum)
print data

输出

[[1, 2, 3], [5, 6, 1], [14, 7]]

编辑以防万一,如果您想知道如何以降序排序,可以使用reverse参数

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)

所以,就您而言

vectors = [generate_vector() for i in range(0, 10)]
print sorted([findbest(vector) for vector in vectors], key=sum)

就这样.

这篇关于Python-根据列表的总和对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆