简体   繁体   中英

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.

  1. Year in format 2020.
  2. Month in integer from 1-12
  3. Any random integer value

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. 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. 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,

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.

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)]
So the output is

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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