简体   繁体   中英

Sorted() function Python

I have a .txt file with the following lines:

pablo 9.50 
sergio 2 
Rose 10 
oto 11.4 
maria 7.9 

and I have the following program:

scores = {}
read = open("C:/Users/renato/Desktop/HTML Files/myfile.txt")
for cont in read: 
    (name,score)=cont.split()
    scores[score] = name
read.close()

print("The top scores are: ")
for eachscore in sorted(scores.keys(), reverse = True):
    print("Surfer "+scores[eachscore]+" scored "+eachscore)

When I run the program, it returns the same list, just as seen on the file.

I'm trying to sort the results, hence I used the sorted() function to sort the keys of the 'scores' dictionary. But the entries are being printed in the same order, not sorted as expected.

Am I'm missing something here?

Thanks!

Are you looking for them to be ordered on the basis of their float value? Then, you're forgetting a call to float() . Without it, the following is the result :

>>> scores
{'11.4': 'oto', '10': 'Rose', '9.50': 'pablo', '2': 'sergio', '7.9': 'maria'}
>>> sorted(scores.keys(), reverse = True)
['9.50', '7.9', '2', '11.4', '10']

As you can see, the numbers are not ordered (because they are in their string representation), but, calling the float() function on them, does the trick.

>>> for cont in f:
        (name, score) = cont.split()
        scores[float(score)] = name


>>> scores
{9.5: 'pablo', 2.0: 'sergio', 11.4: 'oto', 10.0: 'Rose', 7.9: 'maria'}
>>> sorted(scores.keys(), reverse = True)
[11.4, 10.0, 9.5, 7.9, 2.0]

Now, you can just do -

scores = {}
read = open("C:/Users/renato/Desktop/HTML Files/myfile.txt")
for cont in read: 
    (name,score)=cont.split()
    scores[float(score)] = name
read.close()

print("The top scores are: ")
for eachscore in sorted(scores.keys(), reverse = True):
    print("Surfer "+scores[eachscore]+" scored "+str(eachscore))

you must not add scores as dict key

the problem is :

>>> x={'9':'suhail','9':'ta'}
>>> x
{'9': 'ta'}

the key overwrites the old

so the best way is use name as dict key

import operator
scores = {}
read = open("C:/Users/renato/Desktop/HTML Files/myfile.txt")
for cont in read: 
    (name,score)=cont.split()
    scores[name] = float(score)
read.close()

sorted_x = sorted(scores.iteritems(), key=operator.itemgetter(1))
print (sorted_x)

You need to convert the scores to numbers (otherwise, you would be comparing strings):

for eachscore in sorted((float(x) for x in scores.keys()), reverse = True):
    print("Surfer "+scores[eachscore]+" scored "+eachscore)

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