简体   繁体   English

创建一个 function 以循环遍历带有日期的元组列表

[英]Creating a function to loop over a list of Tuples with dates

Hi guys I needed some help.大家好,我需要一些帮助。 I have a list of tuples wherein each tuple contains 3 elements.我有一个元组列表,其中每个元组包含 3 个元素。

  1. Year in format 2020.格式为 2020 的年份。
  2. Month in integer from 1-12 1-12 月 integer
  3. Any random integer value任何随机 integer 值

I wanted to create a function to loop over this list of tuples so that in each tuple I can calculate the difference between the month and the given integer and then find out the new month according to the remainder.我想创建一个 function 来循环遍历这个元组列表,以便在每个元组中我可以计算月份与给定 integer 之间的差异,然后根据余数找出新月份。 For example, the tuple for May 2020 would be (2020,5,3) so then the result would be 5-3=2 which would mean Feb 2020. Also if the result is negative then the year would decrease from 2020 to 2019 and so on according to the difference.例如,2020 年 5 月的元组将是(2020,5,3) ,因此结果将是5-3=2 ,这意味着 2020 年 2 月。此外,如果结果为负数,则年份将从 2020 年减少到 2019 年,并且依此类推。 Any help would be appreciated.任何帮助,将不胜感激。

Edit - So I created this function using the logic given in one of the answers below but it's not exactly what I wanted,编辑 - 所以我使用以下答案之一中给出的逻辑创建了这个 function 但这并不是我想要的,

def subtract_months(input_list):

output_list = []

#TODO: implement your code here

for i in input_list:

    result = i[1]-i[2]

    if 12 >= result > 0:
        output_list.append((i[0],result))
    else:
        output_list.append((i[0]-1,12-abs(result)))

return output_list

If i use an input like [(2020,5,3)] The code works fine and gives an output of (2020,2) but if I want to give input like [(2020,5,20)] then its just looping for one year rather than 2 years.如果我使用 [(2020,5,3)] 之类的输入,则代码可以正常工作并给出 (2020,2) 的 output 但如果我想提供 [(2020,5,20)] 之类的输入,那么它只是循环一年而不是两年。

You can try你可以试试

ls = [(2020,5,3), (2020,5,14), (2020,6,1), (2020,7,18)]
[(i[0], i[1] - i[2], i[2]) if 12 >= i[1] - i[2] > 0 else (i[0] - 1, i[1], i[2])  for i in ls]

The list of tuples in the example is [(2020,5,3), (2020,5,14), (2020,6,1), (2020,7,18)]示例中的元组列表为[(2020,5,3), (2020,5,14), (2020,6,1), (2020,7,18)]
So the output is所以 output 是

[(2020, 2, 3), (2019, 5, 14), (2020, 5, 1), (2019, 7, 18)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM