0

我有一个 .txt 文件,其中包含以下几行:

pablo 9.50 
sergio 2 
Rose 10 
oto 11.4 
maria 7.9 

我有以下程序:

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)

当我运行程序时,它返回相同的列表,就像在文件中看到的一样。

我正在尝试对结果进行排序,因此我使用 sorted() 函数对“分数”字典的键进行排序。但是条目以相同的顺序打印,没有按预期排序。

我在这里遗漏了什么吗?

谢谢!

4

3 回答 3

3

您是否正在寻找根据它们的浮动值订购它们?然后,您会忘记调用float(). 没有它,结果如下:

>>> 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']

如您所见,数字没有排序(因为它们以字符串表示形式),但是,float()在它们上调用函数就可以了。

>>> 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]

现在,你可以这样做 -

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))
于 2013-07-17T04:11:53.017 回答
1

您不能将分数添加为dict key

问题是 :

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

密钥覆盖旧的

所以最好的方法是使用名称作为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)
于 2013-07-17T04:27:32.180 回答
0

您需要将分数转换为数字(否则,您将比较字符串):

for eachscore in sorted((float(x) for x in scores.keys()), reverse = True):
    print("Surfer "+scores[eachscore]+" scored "+eachscore)
于 2013-07-17T04:14:06.377 回答