首页 > 解决方案 > 将值与列表中的项目进行比较

问题描述

我正在尝试在不使用日期时间或日历功能的情况下从 2000 年开始列出 500 年的日历日,但我无法正确遍历 DaysinMonth 列表。我设置了最初的日、月、年,现在想要迭代并将新值附加到一组数组中。

for i in range(len(centday)):
    #if month value is less than 12, the year value= year. If it is 13, add one to the year value. 
    if month <= 12:
        year = year
        yearar.append(year)
    else: 
        year += 1
        yearar.append(year)
        
    #If year is a leap year, change the number of days in months accordingly    
    if year%4 == 0:
        DaysinMonth= [31,29,31,30,31,30,31,31,30,31,30,31]
    else:
        DaysinMonth= [31,28,31,30,31,30,31,31,30,31,30,31]
    
    #set item value    
    j = month - 1  
    listlength = len(DaysinMonth)
    i=0
    if i < listlength:
        if day <= DaysinMonth[i]:
            day = day 
            dayar.append(day)
            monthar.append(month)
        else:
            day = 1
            month += 1
            monthar.append(month)
            i += 1
            if month > 12:
                month = 1
                i = 0

标签: python

解决方案


您的解决方案中的许多复杂性来自于尝试仅使用一个for循环。如果您有年>月>日的嵌套循环,则使用起来会容易得多:

dates = []
start_year = 2000
end_year = 2500

for year in range(start_year, end_year + 1):
    if year % 4 == 0:
        days_in_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    else:
        days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

    for month in range(1, len(days_in_month) + 1)):
        for day in range(1, days_in_month[month] + 1):
            # here we create a date
            dates.append(f"{year}/{month}/{day}")

注意:我假设这是由于不使用日期时间或日历函数的限制而导致的某种问题,但以防万一知道超出闰年和月份长度的日期有很多时髦。如果您遇到需要知道日期是否正确的情况,请使用日期库,因为它们旨在处理可能出现的所有边缘情况。


推荐阅读