Python基础闰年函数错误排查及月份列表格式适配求助
问题修复与代码适配方案
一、闰年判断错误的修复
你的代码把所有年份判定为闰年,核心有两个问题:
- 全局
daysOfMonth被永久修改:第一次处理闰年(比如2020)时,你把列表中二月的天数改成了29,但后续非闰年循环时没有重置回28,导致所有年份的二月都用29天。 - 闰年判断逻辑不完整:仅检查
year % 4 == 0,未遵循完整的闰年规则(整百年需被400整除才是闰年)。
修复后的代码
首先添加完整的闰年判断函数,然后在日历生成时临时计算当月天数,不修改全局列表:
yearList = [2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030] monthList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] def is_leap(year): """判断是否为闰年""" if year % 4 != 0: return False elif year % 100 != 0: return True else: return year % 400 == 0 def create_calendar(yearList: list, monthList: list, daysOfMonth: list, numbOfShootingStars: int): calendar = {} for year in yearList: calendar[year] = {} for month in monthList: # 移除无效的break判断(原逻辑永远不会触发) calendar[year][month] = {} # 临时计算当月天数,不修改全局列表 current_days = daysOfMonth[month - 1] if month == 2 and is_leap(year): current_days = 29 # 生成每日数据 for day in range(1, current_days + 1): calendar[year][month][day] = numbOfShootingStars return calendar
二、适配带月份名称的monthList
你当前写的{1, 'January'}是集合(无序、不可索引),必须改成元组或列表(有序、可索引),推荐用元组(不可变常量更安全)。
修改后的monthList
monthList = [ (1, 'January'), (2, 'February'), (3, 'March'), (4, 'April'), (5, 'May'), (6, 'June'), (7, 'July'), (8, 'August'), (9, 'September'), (10, 'October'), (11, 'November'), (12, 'December') ]
适配后的create_calendar函数
循环时解构元组,同时存储月份数字和名称(也可根据需求选择仅用名称当键):
def create_calendar(yearList: list, monthList: list, daysOfMonth: list, numbOfShootingStars: int): calendar = {} for year in yearList: calendar[year] = {} for month_num, month_name in monthList: calendar[year][month_num] = { 'month_name': month_name, 'days': {} } # 临时计算当月天数 current_days = daysOfMonth[month_num - 1] if month_num == 2 and is_leap(year): current_days = 29 # 生成每日数据 for day in range(1, current_days + 1): calendar[year][month_num]['days'][day] = numbOfShootingStars return calendar
调用后,日历结构会变成:
{ 2020: { 1: { 'month_name': 'January', 'days': {1: 你的流星数, 2: 你的流星数, ...} }, ... }, ... }
内容的提问来源于stack exchange,提问作者mijki
相关产品推荐
相关产品推荐

