I have Created a list which contains all of the information from a scores file in python.
The scores .txt file:
Dan Danson,9,6,1
John Johnson,5,7,10
Mike Mikeson,10,7,6
I did this to get the information from the .txt file into a 2d list:
f = open(filename, 'r')
lines = f.readlines()
f.close()
scores = []
for line in lines: #Loads lines into a 2d list
currentline = line.strip('\n').split(",")
scores.append(currentline)
Now I have this list:
[['Dan Danson', '1', '6', '9'], ['John Johnson', '5', '7', '10'], ['Mike Mikeson', '10', '7', '6']]
From this list I would like to sort the numbers in the list so that they are ordered from highest to lowest so i get a list that looks like this:
[['Dan Danson', '9', '6', '1'], ['John Johnson', '10', '7', '5'], ['Mike Mikeson', '10', '7', '6']]
Finally I want to be able to print the list ordered highest to lowest.
Mike Mikeson,10,7,6
John Johnson,10,7,5
Dan Danson,9,6,1
解决方案
Using sorted with int as a key function:
>>> rows = [
... ['Dan Danson', '1', '6', '9'],
... ['John Johnson', '5', '7', '10'],
... ['Mike Mikeson', '10', '7', '6'],
... ]
>>>
>>> rows = [row[:1] + sorted(row[1:], key=int, reverse=True) for row in rows]
>>> sorted(rows, key=lambda row: sum(map(int, row[1:])), reverse=True)
[['Mike Mikeson', '10', '7', '6'],
['John Johnson', '10', '7', '5'],
['Dan Danson', '9', '6', '1']]
sorted(row[1:], ..): separate number values and sort.
row[:1]: name as a list, alternatively you can use [row[0]]. Should be a list to be concatenated to a list of number strings.