This is my Python code:
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("/"))))
This is the output:
Month = 1, Day = 6, Hours = 10-18
Month = 4, Day = 15, Hours = 10-18
Month = 4, Day = 17, Hours = 10-18
Holidays.txt has the format: month / day / hours
I want to be able to do something like this:
day_input = 6
month_input = 1
if month and day in list_of_holidays:
print(Hours)
-> and have Hours be the corresponding Hours on the same row.I simply can't get this to work how I want it and there's definitely something I'm missing in the code
I simply can't get this to work how I want it and there's definitely something I'm missing in the code.
Is there a way to do this and compare the inputs directly to the list and getting the corresponding Hours?
CodePudding user response:
How you define each instance of Holiday
isn't really relevant, so the solution is the same whether or not you used *map(...)
to provide the arguments to Holiday
.
You just need to check the given month and day against each holiday.
for holiday in list_of_holidays:
if month_input == holiday.month and day_input == holiday.day:
print(holiday.hours)
break # If you know there won't be more than one such holiday