Sorted()函数Python

时间:2013-07-17 04:08:30

标签: python

我有一个包含以下行的.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()函数对“得分”字典的键进行排序。但条目以相同的顺序打印,未按预期排序。

我在这里遗失了什么吗?

谢谢!

3 个答案:

答案 0 :(得分: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))

答案 1 :(得分: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)

答案 2 :(得分:0)

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

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