2015-04-12 108 views
-4

****輸入**** ['From','[email protected]','Fri','Jan','14','22:16:24','2012']如何優化Python代碼?

**** ****計劃

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 

如何優化我的代碼以逐行獲取排序順序中的所需輸出?我需要更改哪些數據結構才能使代碼更好,更緊湊?

回答

0
data = [['From', '[email protected]', 'Fri', 'Jan', '14', '22:16:24', '2012'], 
    ['From', '[email protected]', 'Fri', 'Jan', '14', '23:16:24', '2012'], 
    ['From', '[email protected]', 'Fri', 'Jan', '14', '21:16:24', '2012'], 
    ['From', '[email protected]', '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 
+1

我已經擴展代碼這樣的 - > d = hour_freq_list 爲K,V以排序(d.items()): 打印(K,V),但不知何故,我的系統不喜歡sorted()函數,所以我向你提出了另一個請求。現在,它的工作,一百萬感謝。你是最棒的。我對Python很陌生,所以我可能會要求提供一個好網站列表,可能有幫助的書籍。你將如何從「初學者到掌握」佈局Python旅程。你的洞察力將非常感謝。祝你今天愉快。 – Samuel

+0

非常感謝,但我也是初學者。以下文章列出了一些好看的書。儘管我更喜歡'頭第一蟒蛇',因爲它有點像講故事。無論如何,祝你好運與Python。 (https://freepythontips.wordpress.com/2014/02/04/free-python-books/?relatedposts_hit=1&relatedposts_origin=184&relatedposts_position=2)和(https://freepythontips.wordpress.com/2013/07/31/ 10-python-blogs-worth-following /) – 2015-04-14 07:43:13

+0

再次感謝您分享這些信息。我非常感謝它。作爲一個初學者,你知道很多,我感到非常驚訝。祝你今天愉快。 – Samuel