Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
855 views
in Technique[技术] by (71.8m points)

How do I optimize Python Code?

****Input**** ['From', '[email protected]', 'Fri', 'Jan', '14', '22:16:24', '2012']

****Program****

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)

Current Output

{'19': 1, '04': 3, '14': 1, '11': 6, '18': 1, '09': 2, '17': 2, '15': 2, '10': 3
, '06': 1, '16': 4, '07': 1}

Desired output

04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1

How do I optimize my code to get the desired output in SORTED Order line by line? What data structure do I need to change to make it better and compact code?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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]) )

Output

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...