python - 将值与列表中的项目进行比较
问题描述
我正在尝试在不使用日期时间或日历功能的情况下从 2000 年开始列出 500 年的日历日,但我无法正确遍历 DaysinMonth 列表。我设置了最初的日、月、年,现在想要迭代并将新值附加到一组数组中。
for i in range(len(centday)):
#if month value is less than 12, the year value= year. If it is 13, add one to the year value.
if month <= 12:
year = year
yearar.append(year)
else:
year += 1
yearar.append(year)
#If year is a leap year, change the number of days in months accordingly
if year%4 == 0:
DaysinMonth= [31,29,31,30,31,30,31,31,30,31,30,31]
else:
DaysinMonth= [31,28,31,30,31,30,31,31,30,31,30,31]
#set item value
j = month - 1
listlength = len(DaysinMonth)
i=0
if i < listlength:
if day <= DaysinMonth[i]:
day = day
dayar.append(day)
monthar.append(month)
else:
day = 1
month += 1
monthar.append(month)
i += 1
if month > 12:
month = 1
i = 0
解决方案
您的解决方案中的许多复杂性来自于尝试仅使用一个for
循环。如果您有年>月>日的嵌套循环,则使用起来会容易得多:
dates = []
start_year = 2000
end_year = 2500
for year in range(start_year, end_year + 1):
if year % 4 == 0:
days_in_month = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
else:
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
for month in range(1, len(days_in_month) + 1)):
for day in range(1, days_in_month[month] + 1):
# here we create a date
dates.append(f"{year}/{month}/{day}")
注意:我假设这是由于不使用日期时间或日历函数的限制而导致的某种问题,但以防万一知道超出闰年和月份长度的日期有很多时髦。如果您遇到需要知道日期是否正确的情况,请使用日期库,因为它们旨在处理可能出现的所有边缘情况。
推荐阅读
- java - 灵活数量的 for 循环 - Java
- javascript - 带有 Jest 的 Vuex - 无法读取属性
未定义的 - python-3.x - 如何列出 DataFrame 列表对象中的所有 DataFrame 名称
- java - IntelliJ:调试器在 Maven 项目中不起作用
- bash - 为什么我需要 Root 权限才能执行 `git branch -a`?
- konvajs - 关于 KonvaJS 中的碰撞检测
- azure - 将标志传递给 Azure aci 中的 docker
- codenameone - 地图
转换为地图 我有一张地图
Map<String, String[]> newMetaData = new LinkedHashMap();
我用这样的数据填充:
newMetaData.put( ((String) elm.get("compa
- python - 在嵌套函数中,我想调用内部函数
- jquery - jquery slideToggle 不会回到原始设置