【问题标题】:Calculate Duration in python list计算python列表中的持续时间
【发布时间】:2021-08-30 08:33:58
【问题描述】:

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

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

预计:[4 年 11 个月]

【问题讨论】:

    标签: duration calc


    【解决方案1】:

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

    duration = ['2 years 4 months', '1 year 9 months', '5 months', '2 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个月

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 2015-03-30
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 2013-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多