You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在map()创建的Holiday对象列表中匹配月日并获取对应时长?

问题:根据输入的月日匹配节假日并获取时长

原代码实现

以下是读取节假日文件的Python代码:

class Holiday:
    def __init__(self, month, day, hours):
        self.month = month
        self.day = day
        self.hours = hours

    def __str__(self):
        return f'Month = {self.month}, Day = {self.day}, Hours = {self.hours}'


list_of_holidays = []

with open("Holidays.txt") as afile:
    for line in afile.readlines()[1:]:
        list_of_holidays.append(Holiday(*map(str.strip, line.split("/"))))

上述代码从格式为month / day / hours的Holidays.txt文件中读取数据(跳过首行),通过map()函数创建Holiday对象并存入list_of_holidays列表,输出示例如下:

Month = 1, Day = 6, Hours = 10-18
Month = 4, Day = 15, Hours = 10-18
Month = 4, Day = 17, Hours = 10-18

尝试的错误实现

我希望输入指定的日和月,判断该月日是否存在于list_of_holidays中,若存在则输出对应的时长(Hours),尝试的代码如下:

day_input = 6
month_input = 1

if month and day in list_of_holidays:
    print(Hours)

但无法实现预期效果,请问是否有方法直接将输入值与列表元素匹配并获取对应的时长?


解决方案

错误分析

你的代码存在几个关键问题:

  1. 判断逻辑错误:month and day in list_of_holidays完全不符合需求,list_of_holidays里存的是Holiday对象,不是单独的月份或日期值,无法直接用这种方式判断。
  2. 类型不匹配:输入的day_input和month_input是整数类型,但Holiday对象中的month和day是字符串类型(来自文件读取的字符串处理),直接比较会失败。
  3. 变量未正确引用:代码里的month、day、Hours都是未定义的变量,应该用month_input、day_input以及对象的hours属性。

方法一:遍历列表匹配

直接遍历list_of_holidays中的每个Holiday对象,逐一比较输入的月日与对象的属性:

day_input = 6
month_input = 1

# 遍历列表查找匹配的节假日
for holiday in list_of_holidays:
    # 转成相同类型后比较
    if int(holiday.month) == month_input and int(holiday.day) == day_input:
        print(holiday.hours)
        break
else:
    # 循环正常结束(没找到匹配项)时执行
    print("该日期不是节假日")

方法二:转换为字典提升查询效率

如果需要频繁查询,建议将列表转换为以(month, day)为键、hours为值的字典,这样查询速度更快:

# 将列表转换为字典
holiday_dict = {(int(h.month), int(h.day)): h.hours for h in list_of_holidays}

day_input = 6
month_input = 1

# 查询字典
key = (month_input, day_input)
if key in holiday_dict:
    print(holiday_dict[key])
else:
    print("该日期不是节假日")

内容的提问来源于stack exchange,提问作者Karluk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 13:50:41