这是我的数组:
['','','','','2,509','2.58 hrs / 1.20 days','38','7.78
hrs / 1.16 days','1.28','6.62 mins / 6.62 mins']
我想将整天,分钟转换为小时,该怎么办?
like ['','','','','2,509','2.58 hrs / 28.8 hrs','38','7.78 hrs / 27.84 hrs','1.28','0.110 hrs / 0.110 hrs']
答案 0 :(得分:0)
import re
a = ['','','','','2,509','2.58 hrs / 1.20 days','38','7.78 hrs / 1.16 days','1.28','6.62 mins / 6.62 mins']
def repl(x):
n ={'days':'*24hrs','mins': '/60 hrs'}.get(x.group(2))
n = '' if n is None else n
s = '' if x.group(2) in['mins','days'] else 'hrs'
return x.group(1)+s+n
re.sub(r'(\d\S+)\s([a-z]+)',repl,"\n".join(a)).split('\n')
['',
'',
'',
'',
'2,509',
'2.58hrs / 1.20*24hrs',
'38',
'7.78hrs / 1.16*24hrs',
'1.28',
'6.62/60 hrs / 6.62/60 hrs']
尽管这是您解决方案的复制品,但是要先除还是先乘等意义不大。所以我想括号的介绍会很棒:
def repl(x):
n ={'days':'*24 hrs','mins': '/60 hrs'}.get(x.group(2))
n = '' if n is None else n
if x.group(2)=='hrs': return x.group(1)+x.group(2) + n
return f'({x.group(1)} {n})'
re.sub(r'(\d\S+)\s([a-z]+)',repl,"\n".join(a)).split('\n')
Out[1211]:
['',
'',
'',
'',
'2,509',
'2.58hrs / (1.20*24 hrs)',
'38',
'7.78hrs / (1.16*24 hrs)',
'1.28',
'(6.62/60 hrs) / (6.62/60 hrs)']
如果您需要解决:
a = ['','','','','2,509','2.58 hrs / 1.20 days','38','7.78 hrs / 1.16 days','1.28','6.62 mins / 6.62 mins']
def repl(x):
n ={'days':'*24','mins': '/60'}.get(x.group(2))
n = '' if n is None else n
s = '' if x.group(2) in['mins','days'] else 'hrs'
return str(round(eval(re.sub('[^0-9.]','',x.group(1))+n),4))+'hrs'
re.sub(r'(\d\S+)\s([a-z]+)',repl,"\n".join(a)).split('\n')
['',
'',
'',
'',
'2,509',
'2.58hrs / 28.8hrs',
'38',
'7.78hrs / 27.84hrs',
'1.28',
'0.1103hrs / 0.1103hrs']