问题描述
将字符串(如1:00、3:45)转换为浮点数的最佳方法?我正计划使用此代码(见下文)来计算跑步者2英里和3英里时间的时间,但我需要先将字符串转换为int或float才能在这些计算中使用它。
twoMileTimes=[]
threeMileTimes=[]
for i in range(len(runnerNames)):
twoMileTimes.append(round(twoMileMark[i]-oneMileMark[i],2))
threeMileTime = fiveKMark[i]*(3/3.1)
threeMileTime -= twoMileMark[i]
threeMileTimes.append(round(threeMileTime,2))
解决方法
>>> s = "3:45"
>>> a,b = map(int,s.split(":"))
>>> a
3
>>> b
45
>>> b = b / 60
>>> b
0.75
>>> res = round(a + b,2)
>>> res
3.75
>>>