Python - 一年中每个月的最后一个工作日
给定年份和工作日数字,任务是编写一个Python程序来提取与工作日对应的月份中的每个日期。
Input : year = 1997, weekdy = 5
Output : [’25/1/1997′, ’22/2/1997′, ’29/3/1997′, ’26/4/1997′, ’31/5/1997′, ’28/6/1997′, ’26/7/1997′, ’30/8/1997′, ’27/9/1997′, ’25/10/1997′, ’29/11/1997′, ’27/12/1997′]
Explanation : 5 is friday. Last weekday of january 1997 which is friday is 25.
Input : year = 1996, weekdy = 4
Output : [’26/1/1996′, ’23/2/1996′, ’29/3/1996′, ’26/4/1996′, ’31/5/1996′, ’28/6/1996′, ’26/7/1996′, ’30/8/1996′, ’27/9/1996′, ’25/10/1996′, ’29/11/1996′, ’27/12/1996′]
Explanation : 4 is thursday. Last weekday of january 1997 which is thursday is 26.
方法 #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))
输出:
The original year : 1997
Last weekdays of year : [’25/1/1997′, ’22/2/1997′, ’29/3/1997′, ’26/4/1997′, ’31/5/1997′, ’28/6/1997′, ’26/7/1997′, ’30/8/1997′, ’27/9/1997′, ’25/10/1997′, ’29/11/1997′, ’27/12/1997′]
方法#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))
输出:
The original year : 1997
Last weekdays of year : [’25/1/1997′, ’22/2/1997′, ’29/3/1997′, ’26/4/1997′, ’31/5/1997′, ’28/6/1997′, ’26/7/1997′, ’30/8/1997′, ’27/9/1997′, ’25/10/1997′, ’29/11/1997′, ’27/12/1997′]