我如何优化Python代码?

时间:2015-04-12 22:12:47

标签: python-3.x

**** ****输入 ['From','john @ hotmail.com','Fri','Jan','14','22:16:24','2012']

**** ****方案

words =[]
HMS =[]
hour_freq_list = {}

for line in fHand:  # 1st loop
    line = line.strip()
    if not line.startswith ('From '):continue
    words = line.split()
    HMS = words[5].split()
    Hr, Mi, Se = HMS[0].split(":")

    if Hr in hour_freq_list:
            hour_freq_list[Hr] += 1
    else:
            hour_freq_list[Hr] = 1
print (hour_freq_list)

当前输出

{'19': 1, '04': 3, '14': 1, '11': 6, '18': 1, '09': 2, '17': 2, '15': 2, '10': 3
, '06': 1, '16': 4, '07': 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

如何优化代码以逐行获取SORTED Order中的所需输出?我需要更改哪些数据结构才能使代码更好,更紧凑?

1 个答案:

答案 0 :(得分:0)

data = [['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '22:16:24', '2012'],
     ['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '23:16:24', '2012'],
     ['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '21:16:24', '2012'],
     ['From', 'john@hotmail.com', 'Fri', 'Jan', '14', '22:02:24', '2012']
    ]

hour_frequency_list = {}

for temp in data:
  hour = temp[5].split(":")[0]
  if hour in hour_frequency_list:
     hour_frequency_list[hour] += 1
  else:
     hour_frequency_list[hour] = 1

sorted_list = sorted(hour_frequency_list.items())

print ("hour | Occurences")
for k in sorted_list:
    print (k[0] + "    |" + str(k[1]) )

输出

hour  | Occurences
21    |1
22    |2
23    |1