我有一份名单上写着任期让我给你看-
['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mo']基本上,这些是所有的任期,并将其放入一个列表中,我需要的基本上是- 58,所以在几个月内,总任期是58。
如有任何帮助,将不胜感激。
发布于 2022-05-24 07:20:02
这可以简化,假设“年份”以“y”开头,其他任何东西都必须表示月份。因此:
list_ = ['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mo']
months = 0
for s in list_:
t = s.split()
for a, b in zip(t[::2], t[1::2]):
n = int(a)
if b.startswith('y'):
n *= 12
months += n
print(months)输出:
58发布于 2022-05-24 07:23:30
使用regex:
import re
l = ['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mo']
total = 0
for i in l:
m = re.search(r'(\d+)\s?mo(?:s)?', i) ## find digits before mo/mos
m = m.group(1) if m else 0 ## m=0 if no matches
y = re.search(r'(\d+)\s?yr(?:s)?', i) ## find digits before yr/yrs
y = y.group(1) if y else 0 ## y=0 if no matches
total += (int(m)+12*int(y))
print(total)结果:
58发布于 2022-05-24 07:37:23
您可以尝试解析您的列表,并在特定关键字(如mos和yr )上添加您的总月份。
将列表中的每一项分解为包含关键字和值的列表。假设初始列表格式良好:
list_ = ['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mos']
total = 0
for item in list_:
string = item.split(' ')
for i in range (len(string)):
if string[i] == 'mos':
total += int(string[i-1])
if string[i] == 'yr':
total += 12*int(string[i-1])
print(total)
# 58 https://stackoverflow.com/questions/72358399
复制相似问题