代码:
#read through
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
if not line.startswith('From '): continue
line = line.split()
line = line[5]
time = line.split(':')
time = time[0]
counts[time] = counts.get(time, 0) + 1
print(sorted(counts.items()))
当前输出:
[('04', 3), ('06', 1), ('07', 1), ('09', 2), ('10', 3), ('11', 6), ('14', 1), ('15', 2), ('16', 4), ('17', 2), ('18', 1), ('19', 1)]
所需的输出:
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
我正在做一个作业,我的目标是从文件中提取数据,然后对数据进行计数,排序和列出。我已经基本完成了,但是输出出现了问题。基本上,我无法使代码以所需的垂直格式输出。如何获得所需的输出格式?
此外,如果有更好的方式来做我正在做的事情,请在回答中包括该内容。
谢谢
答案 0 :(得分:1)
尝试一下:
#read through
name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
if not line.startswith('From '): continue
line = line.split()
line = line[5]
time = line.split(':')
time = time[0]
counts[time] = counts.get(time, 0) + 1
for key,value in sorted(counts.items()):
print(key , value)
答案 1 :(得分:1)
尝试一下:
[print(x, y) for x, y in sorted(counts.items())]
您可以使用join()
print('\n'.join([x[0] + " " + str(x[1]) for x in sorted(counts.items())]))