我正在做 Coursera python 练习,这是问题
Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon.>
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
包含文本文件的链接是:http://www.py4inf.com/code/mbox-short.txt
期望的输出如下:
04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1
这是我的代码:
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
count = dict()
lst = list()
for line in handle:
if line.startswith('From '):
word = line.split()
temp = word[5]
time= temp.split(':')
hour = time[0]
count[hour] = count.get(hour, 0) + 1
for k, v in count.items():
lst.append((k, v))
print lst.sort()
但是,我得到的结果是“无”。当我将最后一行更改为:
print lst
结果变成:
[('11', 6), ('10', 3), ('15', 2), ('14', 1), ('04', 3), ('16', 4), ('19', 1), ('18', 1), ('09', 2), ('17', 2), ('06', 1), ('07', 1)]
我用谷歌搜索并找到了这个问题的一个解决方案,如下所示:
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
wds = line.split()
if len(wds) < 5 : continue
if wds[0] != "From" : continue
when = wds[5]
tics = when.split(":")
if len(tics) != 3 : continue
hour = tics[0]
counts[hour] = counts.get(hour,0) + 1
lst = counts.items()
lst.sort()
for key, val in lst :
print key, val
除了文本文件中的循环迭代行之外,我没有看到我的错误代码和我从 github 获得的正确代码之间的功能差异。
有人可以给我一些见解吗?
最佳答案
取自documentation ,调用 lst.sort()
将对列表进行就地排序。这意味着它直接修改列表。您要使用的是 sorted(lst)
,这将返回一个排序列表。
或者,正如评论中指出的那样,调用
lst.sort()
print(lst)
获得您想要的输出。
关于python - 显示基于元组的排序列表并在字典中循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001931/