给定一个如下文件:
(u'castro', 5.4716387933635691)
(u'catcher', 5.4716387933635691)
(u'center', 4.3730265046954591)
(u'caus', 5.0661736852554045)
如何将此文件读取到python字典,然后根据分数对其进行排序?
d={}
with open("scores.txt") as f:
for line in f:
key, val= line.strip().split()
d[key]=val
我试图在这种情况下按val排序,然后以下面的形式得到结果:
(u'castro', 5.4716387933635691)
(u'catcher', 5.4716387933635691)
(u'caus', 5.0661736852554045)
(u'center', 4.3730265046954591)
答案 0 :(得分:2)
这会产生一个嵌套列表:
from operator import itemgetter
with open("scores.txt") as f:
lst = [i.rstrip("\n")[1:-1].split(", ") for i in f.readlines()]
for i in lst:
i[1] = float(i[1])
i[0] = i[0][2:-1]
lst.sort(key=itemgetter(1), reverse=True)
输出:
>>> lst
[['castro', 5.471638793363569], ['catcher', 5.471638793363569], ['caus', 5.0661736852554045], ['center', 4.373026504695459]]
将名称写入文件:
with open("scores2.txt", "w") as f:
for i in lst:
f.write("{}\n".format(i[0]))
答案 1 :(得分:0)
d = sorted(d.items(), key=lambda x: x[1], reverse=True)
答案 2 :(得分:0)
Python词典没有顺序,您只能创建一个排序表示。
import operator
d={}
with open("scores.txt") as f:
for line in f:
key, val= line.strip().split()
d[key]=val
sorted_d = sorted(d.items(), key=operator.itemgetter(0))
print sorted_d