split默认按照空格分割,如果想按照其他标识符分割,需要传入对应字符参数有帮助望采纳
对于list要用索引取成字符串再分割。参考例子如下:
s='''From 12:00
test1
From 12:20
test2
From 13:20
test3
From 14:20
finished
'''
counts={}
for line in s.split('\n'):
if line.startswith('From'):
time=line.split()[-1]
hrs=time.split(':')[0]
counts[hrs]=counts.get(hrs,0)+1
print(counts)
for k,v in sorted(counts.items()):
print(k,v)
运行结果:
F:\2021\qa\ot2>t9
{'12': 2, '13': 1, '14': 1}
12 2
13 1
14 1
如有帮助,请点击采纳。