简体   繁体   中英

Python sort 2D list

I have a list in python 3.6.5 which goes as follows

a_list = [['name1', 5, 6, 3, 7], ['name3', 2, 6, 3, 6], ['name3', 2, 10, 8, 5]]

So it's basically name, score1, score2 etc.

I want to add up the scores and rank they names highest to lowest

So far, I have

a_list.sort(a_list, key=lambda x: x[not sure what to put here], reverse=True)

I need a way of adding up the numbers in the list without affecting the str field.

How can I achieve this?

This should work:

a_list = [['name1', 5, 6, 3, 7], ['name3', 2, 6, 3, 6], ['name3', 2, 10, 8, 5]]
a_list.sort(key=lambda x: sum(x[1:]), reverse=True)
print(a_list)

Output:

[['name3', 2, 10, 8, 5], ['name1', 5, 6, 3, 7], ['name3', 2, 6, 3, 6]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM