我写过这个程序,其中包含铁人三项参与者的字符串和整数信息。有些列表包含参与者的跟踪时间(以秒为单位)。我需要以某种方式将这些时间转换为分钟,并将它们作为浮点数输出2个小数点。
How many participants would you like to display?: 3
Name: Jeff Adrian
Division: M4044
Event: Standard Triathlon
Gender: Male
Swim: 2026 minutes
Transition 1: 329 minutes
Bike: 4625 minutes
Transition 2: 35 minutes
Run: 3847 minutes
Total: 10862.0
由于空间原因,我不打算发布完整列表,但是在下面你可以找到我用来显示参与者信息的循环以及我目前停留的功能:
for i in range(numToDisplay):
ttl += float(swimTimes[i] + transition1Times[i] + cycleTimes[i] + transition2Times[i] + runTimes[i])
print("\n Name: " + str(firstName[i]), str(lastName [i]), "\n", "Division: " + str(division[i]))
if event[i] is 1:
print(" Event: Standard Triathlon")
else:
print(" Event: Sprint Triathlon")
if gender[i] is 1:
print(" Gender: Male")
else:
print(" Gender: Female")
print(" Swim: " + str(swimTimes[i]), "minutes", "\n", "Transition 1: " + str(transition1Times[i]), "minutes", "\n",
"Bike: " + str(cycleTimes[i]), "minutes", "\n", "Transition 2: " + str(transition2Times[i]), "minutes", "\n", "Run: " + str(runTimes[i]), "minutes", "\n",
"Total: " + str(ttl), "\n")
将转换时间转换为分钟的功能:
def secToMin(s):
s = 60
minutes = list[i] / s
float(minutes)
return minutes
如果需要,我很乐意提供有关该计划的更多信息。
答案 0 :(得分:0)
听起来你需要这样的功能:
def secToMin(seconds):
_seconds = seconds
#I wasn't sure if you were storing as string or integer
if type(_seconds) is str:
_seconds = int(_seconds)
secondsRemaining = _seconds%60
minutes = _seconds/60
return "%0.02d minute(s), %0.02d second(s)" %(minutes,secondsRemaining)
然后,如果你有一个时间阵列,你可以一次性转换它们并使用' map'将它们存储到一个单独的数组中。功能:
timesArray = [1000,1500,500,"1400","900"]
newArray = map(secToMin,timesArray)
或者如果你有很多参与者,你可以循环遍历它们并逐一生成它:
Alice = ["Alice",1400]
Bob = ["Bob", 1300]
participants = [Alice, Bob]
for participant in participants:
print secToMin(participant[1])
注意:该函数返回上面的字符串,因为在处理格式化小数位数等事项时处理字符串。您也可以轻松地返回浮点数,如果您稍后需要它们返回一个数组(但是当您处理函数返回的输出时,您需要简单地考虑这个):
def secToMin(seconds):
_seconds = seconds
if type(_seconds) is str:
_seconds = int(_seconds)
secondsRemaining = _seconds%60
minutes = _seconds/60
return ["%0.02d minute(s), %0.02d second(s)" %(minutes,secondsRemaining),float(minutes),float(secondsRemaining)]
希望这就是你要找的东西!