如何在Python3中使输出垂直打印而不是水平打印



代码:

#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

我正在做一项任务,我的目标是从文件中提取数据,然后对数据进行计数、排序和列出。我基本上已经完成了这项任务,但我的输出有问题。基本上,我无法使代码以所需的垂直格式输出。如何获得所需的输出格式?

此外,如果有更好的方法来做我正在做的事情,请在你的回答中包括这一点。

感谢

试试这个:

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

试试这个:

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

最新更新