Python - sort lists based on their sum

后端 未结 2 1939
轻奢々
轻奢々 2021-01-18 18:36

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         


        
2条回答
  •  暖寄归人
    2021-01-18 19:02

    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.

提交回复
热议问题