,所以我有一個這樣的名單:Python的平均值,最大值,最小值從列表
kesto = ['3m 24s', '45s', '1h 2m 40s']
我需要找到一個平均值,最小值和最大值這些。 我曾嘗試:
max_value = max(kesto)
min_value = min(kesto)
avg_value = sum(kesto)/len(kesto)
,但當然這是行不通的,因爲這些都不是數字。他們身後有「m」和「s」。
編輯:此代碼工作正常,但它只返回它獲得的第一個值。 例如,如果有「h」和「m」它只返回「h」 因此1小時20分鐘和1小時15分鐘將是「3600」兩者。
def parse_time(s):
s = s.split()
total = 0
for cl in s:
if cl[-1] == 'd':
total += int(cl[:-1]) * 60 * 60 * 24
if cl[-1] == 'h':
total += int(cl[:-1]) * 60 * 60
if cl[-1] == 'm':
total += int(cl[:-1]) * 60
if cl[-1] == 's':
total += int(cl[:-1])
return total
kesto2 = [parse_time(s) for s in kesto]
'3m 24s = 204'將它們轉換爲int – ksai
是的我知道我必須將它們轉換爲int,但是如何? –