1

我想知道特定日期(在此示例中为今天的日期)是否是世界上某个地方的假期。如果是 - 我想在每个元组中创建带有元组的列表 - (假期名称,世界上的哪个地方)。如果它不是任何地方的假期 - 空列表。我试图导入假期,但我需要像这个例子一样在每个国家运行:有人有更高效的东西吗?

from datetime import date
import holidays

listOfHolidays = []
for ptr in holidays.ISR(years=date.today().year).items():
    if date.today() == ptr[0]:
        listOfHolidays.append(tuple((ptr[1], "ISRAEL")))

for ptr in holidays.US(years=date.today().year).items():
    if date.today() == ptr[0]:
        listOfHolidays.append((tuple(ptr[1], "US")))

for ptr in holidays.UK(years=date.today().year).items():
    if date.today() == ptr[0]:
        listOfHolidays.append((tuple(ptr[1], "UK")))

for ptr in holidays.CHN(years=date.today().year).items():
    if date.today() == ptr[0]:
        listOfHolidays.append((tuple(ptr[1], "CHN")))

print(listOfHolidays)
4

1 回答 1

1

由于holidays包的结构,您确实必须遍历所有受支持的区域。该功能holidays.list_supported_countries可以帮助您解决此问题。好消息是您可以在国家对象中直接查找,而无需手动搜索 dict 项目:

list_of_holidays = []
target = date.today()
for country in holidays.list_supported_countries():
    country = getattr(holidays, country)()
    holiday = country.get(target)
    if holiday is not None:
        list_of_holidays.append((holiday, country.country))

您可以在支持海象运算符的 python 版本中将其写为理解:

list_of_holidays = [(c[target], c.country) for country in holidays.list_supported_countries() 
                                           if target in (c := getattr(holidays, country)())]

问题是这里会有很多重复,因为几乎每个支持的国家都有多种引用方式。这也是一个问题,因为您不想在运行中一遍又一遍地生成相同的列表。

在检查图书馆时,我发现检查 country 类是否“真实”的最可靠方法是通过该方法检查它是否引入了任何新的假期_populate。您可以为此添加条件:

list_of_holidays = []
target = date.today()
for country in holidays.list_supported_countries():
    country_obj = getattr(holidays, country)
    country = country_obj()
    holiday = country.get(target)
    if holiday is not None and '_populate' in country_obj.__dict__:
        list_of_holidays.append((holiday, country.country))

或者作为一种理解:

list_of_holidays = [(c[target], c.country) for country in holidays.list_supported_countries()
                        if target in (c := getattr(holidays, country)()) and '_populate' in c.__class__.__dict__]

country最后,当您使用该属性时,国家代码始终作为名称给出。如果您想要更清晰的东西,我发现最好使用实现该_populate方法的类的名称。对于第二个循环,替换(holiday, country.country)

(holiday, country_obj.__name__)

对于第二个列表理解,替换(c[target], c.country)

(c[target], c.__class__.__name__)
于 2021-12-05T20:19:43.583 回答