无法弄清楚如何使用Python

时间:2015-08-10 16:43:12

标签: python python-2.7 sorting

我试图以hh:mm:ss格式从电子邮件中获取时间码并解析小时。然后我把它放在一本字典中,这样就可以显示每小时有多少封电子邮件,然后将其打印在一个列表中,然后将其打印出来:

04 3
06 1
07 1
09 1
10 3
11 6

我需要按小时/值排序,并使用旧的x.sort()函数列表。课程使用的自动编程器不支持sorted()。目前它似乎完全忽略了.sort()命令:

11 6 
10 3 
15 2
14 4

这是我的完整代码:

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()

for line in handle:
    line = line.rstrip()
    words = line.split()
    if words == [] : continue
    if words[0] != 'From' : continue
    full = words[5:6]
    allitems = ".".join(full)
#    print allitems
    for linee in allitems:
        linee = allitems.rstrip()
#        if linee in counts : continue
        wordss = linee.split(':')
        cutt = wordss[0:1]
        print cutt
    for val in cutt :
        counts[val] = counts.get(val, 0 ) + 1
print counts

lst = list()
for hour, frequency in counts.items() :
    newtup = (hour, frequency)
    lst.append(newtup)

lst.sort
print lst
for howr, freq in lst:
    print howr, freq

这里出了什么问题?

2 个答案:

答案 0 :(得分:1)

您需要调用sort()方法,截至目前,您只是获取对list.sort函数的引用,而不对其执行任何操作,示例 -

lst.sort()

答案 1 :(得分:0)

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)

counts = dict()

for line in handle:
    line = line.rstrip()
    wrds = line.split()
    if words == [] : continue
    if words[0] != 'From' : continue
    full = words[5:6]
    allitems = ".".join(full)
#    print allitems
    for linee in allitems:
        linee = allitems.rstrip()
#        if linee in counts : continue
        wordss = linee.split(':')
        cutt = wordss[0:1]
        #print cutt
    for val in cutt :
        counts[val] = counts.get(val, 0 ) + 1
#print counts

lst = list()
for hour, frequency in counts.items() :
    newtup = (hour, frequency)
    lst.append(newtup)

lst.sort()
#print lst
for howr, freq in lst:
    print howr, freq


    python