首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python中找出包含年份和月份作为字符串的总月。

在python中找出包含年份和月份作为字符串的总月。
EN

Stack Overflow用户
提问于 2022-05-24 06:55:50
回答 3查看 29关注 0票数 -1

我有一份名单上写着任期让我给你看-

代码语言:javascript
复制
['5 mos', '1 yr 8 mos', '9 mos', '11 mos', '1 yr 1 mo']

基本上,这些是所有的任期,并将其放入一个列表中,我需要的基本上是- 58,所以在几个月内,总任期是58。

如有任何帮助,将不胜感激。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-05-24 07:20:02

这可以简化,假设“年份”以“y”开头,其他任何东西都必须表示月份。因此:

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
58
票数 1
EN

Stack Overflow用户

发布于 2022-05-24 07:23:30

使用regex:

代码语言:javascript
复制
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)

结果:

代码语言:javascript
复制
58
票数 1
EN

Stack Overflow用户

发布于 2022-05-24 07:37:23

您可以尝试解析您的列表,并在特定关键字(如mos和yr )上添加您的总月份。

将列表中的每一项分解为包含关键字和值的列表。假设初始列表格式良好:

代码语言:javascript
复制
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 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72358399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档