用Python从年中减去月份

2024-09-28 21:49:29 发布

您现在位置:Python中文网/ 问答频道 /正文

实现函数subtract_months从给定的年和月减去n个月数

输入:是元组的列表[(year1, month1, months_to_subtract1), (year2, month2, months_to_subtract2), ...] 其中,年是一个4位整数 月是介于1到12之间的整数值,1=一月,2=二月。。。12(12月)和 月到月是一个整数

输出:是元组的列表[(result_year1, result_month1), (result_year2, result_month2), ...] 年(4位整数)月(1到12之间的整数值,1=一月,2=二月,…12=十二月)

例如:从2020年5月起减去3个月。这将导致2020年2月的产出 在本例中,输入:年=2020月=5 产量:年=2020月=2

def subtract_months(input_list):
    output_list = []
    #TODO: implement your code here

    return output_list

Tags: to函数列表output整数resultlist元组
3条回答

我提出的解决方案,适用于所有情况

def减去月份(年、月、月减去):

result_month = 0
result_year = 0
if month > (month_to_subtract % 12):
    result_month = (month - month_to_subtract) % 12 
    result_year = year - month_to_subtract // 12
else:        
    result_month = 12 - (month_to_subtract % 12) + month
    result_year = year - (month_to_subtract // 12 + 1)
    
return (result_year, result_month)

减去月数(2010,5,7)

(2009,10)

def subtract_months(input_list):
    output_list = []
    #TODO: implement your code here
    year = [a_tuple[0] for a_tuple in input_list]
    month = [a_tuple[1] for a_tuple in input_list]
    month_to_subtract = [a_tuple[2] for a_tuple in input_list]
    for i in range(len(year)):
        result_month = 0
        result_year  = 0
        if month[i] > (month_to_subtract[i] % 12):
            result_month = (month[i] - month_to_subtract[i]) % 12
            result_year = year[i] - month_to_subtract[i] // 12
        else:
            result_month = 12 - (month_to_subtract[i] % 12) + month[i]
            result_year = year[i] - (month_to_subtract[i] // 12 + 1)
        output_tuple=(result_year,result_month)
        output_list.append(output_tuple)

    return output_list

虽然Shubham的逻辑是正确的,但我想改进它,因为输入是一个元组列表,输出也是一个元组列表。因此,我们将给出一个元组列表作为参数,然后对元组和列表进行迭代,而不是对函数的3个参数进行硬编码。此外,这应该返回一个元组列表

def subtract_months(input_list):
list = []
output_list = []
for i in input_list:
    for j in i:
        list.append(j)
    if list[1] > (list[2] % 12) :
        result_month = (list[1] - list[2]) % 12
        result_year = list[0] - list[2] // 12
    else:
        result_month = 12 - (list[2] % 12 ) + list[1]
        result_year = list[0] - (list[2] // 12 + 1)
    listed = (result_year, result_month)
    output_list.append(listed)
    list = []
    
return output_list

相关问题 更多 >