在python列表中计算持续时间

问题描述

建议一个简单的逻辑来总结持续时间

输入:['2年4个月','1年9个月','5个月','2个月','2个月',1个月]

预期:[4 年 11 个月]

解决方法

这不是优化的解决方案,但它简单且有效。

duration = ['2 years 4 months','1 year 9 months','5 months','2 months','1 month']


years = 0
months  = 0

# splitting each value by space

for item in duration:
    # data will a hold a list of all the years and months with the string 'year' and 'month'
    # example  - ['2','years','4','months']
    data = item.split(' ')
    
    # if years mentioned in data that means there is a year to add in the sum 
    if 'year' in data or 'years' in data:
        # the first value of the data list is a year
        # adding year to the sum of years
        years+=int(data[0])

    # if months mentioned in data that means there is a month value to add in the months
    if 'month' in data or 'months' in data:
        # unlike years month can be on 0th index or 2th index
        # so the value of month can be (index of 'months' or 'month') - 1  
        index = data.index('month') if 'month' in data else data.index('months')
        months+=int(data[index-1])


# If months are more than 12 we need to increase a year accordingly
# so we can just devide the months by 12 the result will be years to add remainder will be months 

if months >= 12:
    #doing integer devision so we don't get the value in decimal
    years += months // 12
    months = months % 12

print(years,"years",months,"months")

输出 4年11个月