PR4E第十周笔记

来源:互联网 发布:汽车票制作生成器软件 编辑:程序博客网 时间:2024/06/06 07:54

转眼间就课程最后一周了啊

这周内容是元组,挺简单的就是元组类似列表,但是不可修改。可以进行比较运算


本周作业

10.2 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. Note that the autograder does not have support for the sorted() function.

最后做的结果是:

name = raw_input("Enter file:")if len(name) < 1 :     name = "mbox-short.txt"handle = open(name)#use dictionary to counthrs = dict()for line in handle:    if line.startswith("From") and not line.startswith("From:"):        temp = line.split()        hrs[temp[5][0:2]] = hrs.get(temp[5][0:2],0)+1        #sort the keyrank = hrs.items()rank.sort()for k,v in rank:    print k,v

这次遇到不少问题,其中有:if语句忘了加and之类的无关痛痒但是十分蛋疼的错误。值得一提的是:一开始忘记了截取字符串string[:]是左闭右开而导致只截取了一个字符,忘记了用items能把字典变成列表,想用for k,v in hrs把(k,v)元组添加到rank列表中,可是总是失败,得出来的k,v不是字典中的key与value,而分别是key的前两个数字0和1,而后百度得知多变量的循环参数循环的是一个元组(k,v),但是为什么在key为”01“时k和v会被赋值为0和1还是不得而知。。。

0 0
原创粉丝点击