简体   繁体   中英

How to get output to print vertically instead of horizontally in Python 3?

Code:

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

Current Output:

[('04', 3), ('06', 1), ('07', 1), ('09', 2), ('10', 3), ('11', 6), ('14', 1), ('15', 2), ('16', 4), ('17', 2), ('18', 1), ('19', 1)]

Desired Output:

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

I am working on an assignment where my goal is to extract data from a file then count the data, sort it and list it. I've basically accomplished this but I am having issues with the output. Basically, I am unable to get the code to output in the desired output of a vertical format. How do I go about getting the desired output format?

Furthermore, if there is a better way of doing what I am doing please include that in your answer.

Thanks

Try this:

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

Try this:

[print(x, y) for x, y in sorted(counts.items())]

Instead of printing in each iteration you can convert list to string using join()

print('\n'.join([x[0] + " " + str(x[1]) for x in sorted(counts.items())]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM