Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python从年中减去月份_Python_Python 3.x - Fatal编程技术网

用Python从年中减去月份

用Python从年中减去月份,python,python-3.x,Python,Python 3.x,执行功能subtract_months从给定年份和月份中减去n月数 输入:是元组列表[(year1,month1,months\u-to\u-subtract1),(year2,month2,months\u-to\u-subtract2),…] 其中,年是一个4位整数 月是介于1到12之间的整数值,1=一月,2=二月。。。12(12月)和 月到月是一个整数 输出:是元组列表[(结果年1,结果月1),(结果年2,结果月2),…] 年(4位整数)月(1到12之间的整数值,1=一月,2=二月,…12

执行功能
subtract_months
从给定年份和月份中减去
n
月数

输入:是元组列表
[(year1,month1,months\u-to\u-subtract1),(year2,month2,months\u-to\u-subtract2),…]
其中,年是一个4位整数 月是介于1到12之间的整数值,1=一月,2=二月。。。12(12月)和 月到月是一个整数

输出:是元组列表<代码>[(结果年1,结果月1),(结果年2,结果月2),…] 年(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
我提出的解决方案,适用于所有情况。 def减去月份(年、月、月减去):

减去月数(2010,5,7)

(2009,10)

def减去月份(输入列表):
输出列表=[]
#TODO:在这里实现您的代码
年份=[a_tuple[0]表示输入列表中的a_tuple]
month=[a_tuple[1]表示输入列表中的a_tuple]
月到月减去=[输入列表中的一个元组的一个元组[2]
对于范围内的i(len(年)):
结果_月=0
结果_年=0
如果月[i]>(月[i]%减去[i]%12):
结果月=(月[i]-月[u]减去[i])%12
结果年=年[i]-月[u]减去[i]//12
其他:
结果月=12-(月至月减去[i]%12)+月[i]
结果年=年[i]-(月-i减去[i]//12+1)
输出参数=(结果年、结果月)
输出\列表.追加(输出\元组)
返回输出列表

虽然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

如果你在自己解决这个问题时遇到了一个特定的问题,你可以在这里提问。你可以使用代码块来放置代码,使你的答案看起来比格式化好,最好在你的解决方案中添加一个解释,以便其他人可以概括他们自己的问题
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