基于Python中的zip函数从列表中的字符串文本中提取数字

2024-09-22 20:36:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以分和秒表示时间的字符串列表,例如

distanceList = [0.56, 0.04, 0.56, 0.44, 0.76] #represents distances traveled
timeList = ['5m:11s', '18m:18s', '13m:35s', '8m:26s', '121m:7s'] # represents time to taken to travel

我需要提取这些数字(分(m)和秒(s))并转换成小时。你知道吗

到目前为止,我已经实现了zip函数,并使用了一些列表理解来将数字单独提取到列表中。然而,我不知道如何把这些时间加起来,因为它们是分开的,而且与结肠分隔符的距离并不总是一致的。我就这么走了。你知道吗

for a, b in zip(distanceList, timeList):
nums = [item for subitem in b for item in subitem.split() if item.isdigit()]
print nums

预期结果:表示分和秒的整数列表。你知道吗

[[5,11],[18,18]...]

收到的结果:

['5', '1', '1', '1', '8', '8'....]

Tags: to字符串in列表for时间数字zip
3条回答

如果“summing into hours”仍然相关:sumtimedelta对象。你知道吗

from datetime import timedelta

strings =  ['5m:11s', '18m:18s', '13m:35s', '8m:26s', '121m:7s']

def sum_timestrings(strings):
    min_secs = (s.split(':') for s in strings)
    total = sum((timedelta(minutes=int(m[:-1]), seconds=int(s[:-1]))
                for m, s in min_secs), timedelta())
    return total

total = sum_timestrings(strings)
print(total) # 2:46:37 
print(total.total_seconds()/3600) # 2.7769444444444447 

加5美分

times = ['5m:11s', '18m:18s', '13m:35s', '8m:26s', '121m:7s']
f = lambda x : int(''.join([i for i in x if i.isdigit()]))
new_times = [[f(s) for u in t.split(":") for s in u.split() ] for t in times]

输出

[[5, 11], [18, 18], [13, 35], [8, 26], [121, 7]]
time_strings = ['5m:11s', '18m:18s', '13m:35s', '8m:26s', '121m:7s']

times = []

for time_string in time_strings:
    tokens = time_string.replace("m", "").replace("s", "").split(":")
    minutes, seconds = map(int, tokens)
    times.append([minutes, seconds])

print(times)

或:

time_strings = ['5m:11s', '18m:18s', '13m:35s', '8m:26s', '121m:7s']

times = []

for time_string in time_strings:
    tokens = time_string.split(":")
    minutes, seconds = map(int, [token.strip("ms") for token in tokens])
    times.append([minutes, seconds])

print(times)

输出:

[[5, 11], [18, 18], [13, 35], [8, 26], [121, 7]]

相关问题 更多 >