在 python..寻找一个简单的代码来从日期时间输出字符串并从列表中浮动
In python..looking for a simple code to output string from datetime and float from a list
我想遍历前五个列表中的每个平均值(索引[0])和每小时(索引[1])(按此顺序):
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']]
我想使用 str.format() 方法以下列格式打印小时和平均值:
输出 str =“15:00:每个 post”的平均评论数为 38.59“
要格式化小时,我可以使用 datetime.strptime() 构造函数到 return 日期时间对象,然后使用 strftime() 方法指定时间格式。
要格式化平均值,我可以使用 {:.2f} 来指示只应使用两位小数。
如何用 2-3 行代码完成此操作?
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))
输出示例:
15:00:每个 post
的平均评论数为 38.59
鉴于数据,使用 datetime
有点矫枉过正:
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
我想遍历前五个列表中的每个平均值(索引[0])和每小时(索引[1])(按此顺序): 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']]
我想使用 str.format() 方法以下列格式打印小时和平均值: 输出 str =“15:00:每个 post”的平均评论数为 38.59“
要格式化小时,我可以使用 datetime.strptime() 构造函数到 return 日期时间对象,然后使用 strftime() 方法指定时间格式。
要格式化平均值,我可以使用 {:.2f} 来指示只应使用两位小数。 如何用 2-3 行代码完成此操作?
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))
输出示例: 15:00:每个 post
的平均评论数为 38.59鉴于数据,使用 datetime
有点矫枉过正:
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