LaVOZs

The World’s Largest Online Community for Developers

'; In python..looking for a simple code to output string from datetime and float from a list - LavOzs.Com

I would like to loop through each average(index[0]) and each hour(index[1]) (in this order) in the first five lists of: a = [[38.59, '15'], [23.81, '02'], [21.52, '20'], [16.8, '16'], [16.01, '21'], [14.74, '13'], [13.44, '10'], [13.24, '18'], [13.23, '14'], [11.46, '17']]

I would like to use the str.format() method to print the hour and average in the following format: output str = "15:00: 38.59 average comments per post"

To format the hours, I can use the datetime.strptime() constructor to return a datetime object and then use the strftime() method to specify the format of the time.

To format the average, I can use {:.2f} to indicate that just two decimal places should be used. How can I accomplish this with 2-3 lines of coding?

from datetime import datetime as dt

a = [[38.59, '15'], [23.81, '02'], [21.52, '20'], [16.8, '16'], [16.01, '21'], [14.74, '13'], [13.44, '10'], [13.24, '18'], [13.23, '14'], [11.46, '17']]
for elem in a[:5]:
    dtObj = dt.strptime(elem[1], '%H')
    timeString = dt.strftime(dtObj, '%H:%M')
    roundedAverageString = "{0:.2f}".format(elem[0])
    print("{}: {} average comments per post".format(timeString, roundedAverageString))

output example: 15:00: 38.59 average comments per post

Using datetime is overkill given the data:

data = [[38.59, '15'], [23.81, '02'], [21.52, '20'], [16.8, '16'], [16.01, '21'], [14.74, '13'], [13.44, '10'], [13.24, '18'], [13.23, '14'], [11.46, '17']]
for ave,hr in data[:5]:
    print(f'{hr}:00: {ave:5.2f} average comments per post')
15:00: 38.59 average comments per post
02:00: 23.81 average comments per post
20:00: 21.52 average comments per post
16:00: 16.80 average comments per post
21:00: 16.01 average comments per post
Related
How would you make a comma-separated string from a list of strings?
How do I calculate the date six months from the current date using the datetime Python module?
Converting from a string to boolean in Python?
How to delete a character from a string using Python
Remove empty strings from a list of strings
Remove specific characters from a string in Python
Check if a Python list item contains a string inside another string
Python datetime to string without microsecond component
Convert datetime object to a String of date only in Python