将文件读入词典并尝试运行

2024-04-28 12:01:48 发布

您现在位置:Python中文网/ 问答频道 /正文

给定一个如下所示的文件:

(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)

Tags: 文件keytxt字典排序withlineval
3条回答
d = sorted(d.items(), key=lambda x: x[1], reverse=True)

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

这将生成嵌套列表:

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

相关问题 更多 >