gpt4 book ai didi

Python:将 "- hrs - min - sec' 字符串更改为分钟十进制

转载 作者:行者123 更新时间:2023-11-28 21:09:51 25 4
gpt4 key购买 nike

我目前正在用 Python 开发一个项目(必须自学 Python,目前仍在学习),该项目从给我的 csv 文件中获取数据。

我目前对如何遍历列表以将列表中的字符串(例如“2 小时 5 分 15 秒”)转换为小数并将其保存为另一个列表/数组感到困惑。

我知道 H:M:S,但在列表的某些区域,它只是“8 分 4 秒”,因此它从有小时计数到只有分钟和秒不等。

最佳答案

函数:

def hms_to_mins(t):
h, m, s = [int(i) for i in t.split(' ')]
return float(60*h + m + (s/60))

hms_to_mins('5 30 0')

输出:330.0

您可以添加更多内容来验证输入并检查是否有 3 个输入(小时、分钟和秒)。

如果您想将输入作为“5hrs 30mins 2sec”并运行,在上面的代码中只需使用这个(而不是 hms_to_mins('5 30 0')):

import re
t=' '.join(re.findall('\d+', s))
hms_to_mins(t)

所以代码应该是:

import re

def hms_to_mins(t):
h, m, s = [int(i) for i in t.split(' ')]
return float(60*h + m + (s/60))

s='5hrs3mins0sec' //your time string
t=(re.findall('\d+', s))
while(len(t)<3): t.append(str(0))
t=' '.join(t)

hms_to_mins(t)

输出:303.0

关于Python:将 "- hrs - min - sec' 字符串更改为分钟十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37474558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com