gpt4 book ai didi

python - 用年份注释月份列表

转载 作者:行者123 更新时间:2023-12-02 13:31:33 25 4
gpt4 key购买 nike

我有一个连续几个月的列表,始终包括当月。例如,当我写这篇文章时,时间是 2020 年 4 月,因此有效列表可以是以下任意列表:

example1 = ["January", "February", "March", "April", "May"]
example2 = ["December", "January", "February", "March", "April"]
example3 = ["April", "May", "June", "July", "August", "September", "October", "November", "December", "January", "February"]

编写 Python 函数的最佳方法是什么,给定一个这样的列表,该函数将返回相应的年份列表,以当前月份为当前年份。例如:

f(example1) = [2020, 2020, 2020, 2020, 2020]
f(example2) = [2019, 2020, 2020, 2020, 2020]
f(example3) = [2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2021, 2021]

我能想到的最好的方法是按当前月份对原始列表进行分区,然后在每个方向上循环,同时还跟踪年份,然后将两个结果列表放在一起。但这太多循环了。有更优雅/更快的解决方案吗?

最佳答案

作为一名 Python 初学者,我一直有些困惑。我认为逻辑是:

  • 查找您当前工作月份的索引,例如:四月
  • 将其设置为当前年份
  • 使用 if...elif... 结构循环遍历列表的其余部分,根据当前月份的哪一侧生成值。

我按照this使用了from dateutil.relativedelta importrelativedelta关于 SO 的旧帖子。

import datetime as dt
from dateutil.relativedelta import relativedelta

def get_years_for(months):
today = dt.date.today()
try:
month_index = months.index(today.strftime("%B"))
except ValueError:
return []

current_month = today.month
current_year = today.year
day1 = dt.date(current_year, current_month, 1)

years = {month_index: current_year}

for idx, month in enumerate(months):
if idx < month_index:
years[idx] = (day1 - relativedelta(months=month_index - idx)).year
elif idx > month_index:
years[idx] = (day1 + relativedelta(months=idx - month_index)).year

return [years[i] for i in sorted(years)]

我确信这可以做得更简洁,但我喜欢这个挑战,因为我是新手 =)

<小时/>
example1 = ["January", "February", "March", "April", "May"]
[2020, 2020, 2020, 2020, 2020]
<小时/>
example2 = ["December", "January", "February", "March", "April"]
[2019, 2020, 2020, 2020, 2020]
<小时/>
example3 = ["April", "May", "June", "July", "August", "September", "October", "November", "December", "January", "February"]
[2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2021, 2021]
<小时/>
example4 = ["November", "December", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", "January", "February"]
[2019, 2019, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2020, 2021, 2021]
<小时/>

所有这些都是在当前月份的假设下完成的,例如四月,仅在您的列表中出现一次(根据您的解释)。即便如此,只要我们可以安全地假设四月的第一个指数是您的起始位置,它仍然有效。

希望有帮助。

关于python - 用年份注释月份列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60987700/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com