如何解决在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个月
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。