📜  Python - 一年中每个月的最后一个工作日

📅  最后修改于: 2022-05-13 01:55:28.214000             🧑  作者: Mango

Python - 一年中每个月的最后一个工作日

给定年份和工作日数字,任务是编写一个Python程序来提取与工作日对应的月份中的每个日期。

方法 #1:使用循环 + max() + calendar.monthcalendar

在此,我们使用来自日历库的 monthcalendar() 执行获取每个月历的任务。提取每个工作日的日期,其中最大值,即整个月的最大值是最后一个工作日,因此提取。

Python3
# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using loop + max() + calendar.monthcalendar
import calendar
  
# initializing year
year = 1997
  
# printing Year
print("The original year : " + str(year))
  
# initializing weekday 
weekdy = 5
  
# iterating for all months
res = []
for month in range(1, 13):
      
    # max gets last friday of each month of 1997
    res.append(str(max(week[weekdy] 
                       for week in calendar.monthcalendar(year, month))) +
               "/" + str(month)+ "/" + str(year))
  
# printing 
print("Last weekdays of year : " + str(res))


Python3
# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using list comprehension
import calendar
  
# initializing year
year = 1997
  
# printing Year
print("The original year : " + str(year))
  
# initializing weekday 
weekdy = 5
  
# list comprehension for shorthand
res = [str(max(week[weekdy]
               for week in calendar.monthcalendar(year, month))) + 
       "/" + str(month)+ "/" + str(year) for month in range(1, 13)]
  
# printing 
print("Last weekdays of year : " + str(res))


输出:

方法#2:使用列表理解

与上述方法类似,唯一的区别是使用列表理解来实现紧凑的解决方案。

蟒蛇3

# Python3 code to demonstrate working of
# Last weekday of every month in year
# Using list comprehension
import calendar
  
# initializing year
year = 1997
  
# printing Year
print("The original year : " + str(year))
  
# initializing weekday 
weekdy = 5
  
# list comprehension for shorthand
res = [str(max(week[weekdy]
               for week in calendar.monthcalendar(year, month))) + 
       "/" + str(month)+ "/" + str(year) for month in range(1, 13)]
  
# printing 
print("Last weekdays of year : " + str(res))

输出: