问题。
Class Confidence Xmin Ymin Xmax Ymax
6 0.9917297 62 0 81 76
1 0.99119675 0 41 8 83
9 0.8642462 23 31 46 98
4 0.8287333 22 30 45 95
我的预期输出是:
1 0.99119675 0 41 8 83
4 0.8287333 22 30 45 95
9 0.8642462 23 31 46 98
6 0.9917297 62 0 81 76
我的代码被给出了:
from collections import defaultdict
import os
for root, dirs, files in os.walk(r'F:GGRprocess'): # this recurses into subdirectories as well
for f in files:
maxima = defaultdict(int)
try:
with open(os.path.join(root,f)) as ifh:
for line in ifh:
key, value = line.rsplit(None, 1)
value = int(value)
if value > maxima[key]:
maxima[key] = value
with open(os.path.join(root, f'{f}.out'), 'w') as ofh:
for key in sorted(maxima):
ofh.write('{} {}n'.format(key, maxima[key]))
except ValueError:
# if you have other files in your dir, you might get this error because they
# do not conform to the structure of your "needed" files - skip those
print(f, "Error converting value to int:", value)
运行此脚本后,输出将显示:
1 0.99119675 0 41 8 83
4 0.8287333 22 30 45 95
6 0.9917297 62 0 81 76
9 0.8642462 23 31 46 98
我不明白我的代码中有什么问题。请解决此问题,我该如何获得此程序的预期输出?
您正在获取由于此行所述的输出:
for key in sorted(maxima):
这意味着,如果您的密钥是6, 1, 9, 4
,它们将成为1, 4, 6, 9
,这是恰好 它们在您显示的输出中显示的顺序。您想要的是读取和输出以添加的顺序。,如果您使用的是Python3.6及更大,请删除sorted
和输出将按添加数据的顺序打印。
如果您使用的是较早版本的Python3,则需要一个容器,该容器可以跟踪添加键和值的顺序,sorted
的删除。那就是使maxima
成为OrderedDict
(这是来自collections
软件包(,和将将键打印到for key in maxima
的for循环。