Python - sort lists based on their sum

后端 未结 2 1938
轻奢々
轻奢々 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.

    0 讨论(0)
  • 2021-01-18 19:04
    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)
    
    0 讨论(0)
提交回复
热议问题