Keeping Name And Score Together While Sorting
so I need to sort some high scores into order and here is the code I already have: def sortscores(): namelist = [] scorelist = [] hs = open('hst.txt', 'r') hscounte
Solution 1:
If you store your high scores in (name, score) tuples, then you can easily keep them together. Since you need to write the sort function yourself, it might be helpful to look at an example of using tuples in another problem. Here's an example of simply finding the maximum score while keeping the name and scores together.
First, set up the data. You can use zip for this
names = ['John', 'Jane', 'Tim', 'Sara']
scores = [100, 120, 80, 90]
data = list(zip(names, scores)) # For Python 2.X you don't need the 'list' constructor
print(data)
Outputs:
[('John', 100), ('Jane', 120), ('Tim', 80), ('Sara', 90)]
Now find the maximum entry:
max_entry = ('', 0)
for entry in data:
if entry[1] > max_entry[1]:
max_entry = entry
print(max_entry)
Outputs:
('Jane', 120)
Solution 2:
you could make a copy of your dict, find the biggest value, save the key to a list, remove the key from the dict and then do that again until the copied dict is empty.
import copy
scores = {'hawks': 23, 'eagles': 42, 'knights': 33, 'rabbits': 44} #this or read from .txt
scorescopy = copy.deepcopy(scores) #makes a copy of the dict, so you don't change the dict when deleting keys from the copy
rank = [] #the list in which we want the keys ranked by value
def keywithmaxval(scores): #finde the key with the highest value (stolen from another stackoverflow question)
values = list(scores.values())
keys = list(scores.keys())
return keys[values.index(max(values))]
while len(scorescopy) > 0: #repeats until copy of dict is empty
maxkey = keywithmaxval(scorescopy)
scorescopy.pop(maxkey) #deletes key from copy of dict
rank.append(maxkey) #puts key in the ranked list
print 'rank', rank #list of keys ranked by value
print 'copy of dict', scorescopy #copy of dict, should be empty after we looped trough
print 'original dict',scores #original dict, should be unchanged
print '\nRank:'
for key in rank: print key,':',scores[key] #pretty list of keys and vals
Post a Comment for "Keeping Name And Score Together While Sorting"