迭代yeardatescalendar重复日期

时间:2014-08-07 02:16:42

标签: python

为什么输出中的某些日期会重复,是否有任何(干净的)方法来修改以下脚本来修复它?我不想将输出放在列表中并找到唯一的日期或类似的东西。想知道循环本身是否可以被修改。

import calendar

c = calendar.Calendar()
for item in c.yeardatescalendar(2014):
    for i1 in item:
        for i2 in i1:
            for i3 in i2:
                if 'Fri' in i3.ctime():
                    print i3

这是输出,注意一些日期重复:

2014-01-03
2014-01-10
2014-01-17
2014-01-24
2014-01-31
2014-01-31
2014-02-07
2014-02-14
2014-02-21
2014-02-28
2014-02-28
2014-03-07
2014-03-14
2014-03-21
2014-03-28
2014-04-04
2014-04-04
2014-04-11
...

1 个答案:

答案 0 :(得分:0)

这个问题源于这样一个事实,即python的月/年等想法总是包括整周。因此,2月份的名单实际上可能有1月份的日期等。实际上,2015年的某些日期恰好在2014年的列表中。缓解这种方式的唯一方法是在另一个数据结构中累积星期五以消除重复

一个简单的方法是一套。集合是没有重复但没有订单的项目集合。如果您想了解更多信息,请查看python documentation。因此,我们将创建一组星期五,对它们进行排序,然后将它们打印出来以获得所需的效果。

以下是代码:

import calendar

cal = calendar.Calendar()

fridays = set() # Constructs a new, empty set

# build a list of months, which are a list of weeks, etc.
months = [cal.monthdatescalendar(2014, month) for month in range(1, 13)]
for month in months:
    for week in month:
        for day in week:
            if day.weekday() == 4 and day.year == 2014:
                fridays.add(day)

for friday in sorted(fridays): # iterate through sorted fridays
    print friday

结果:

2014-01-03
2014-01-10
2014-01-17
2014-01-24
2014-01-31
2014-02-07
2014-02-14
2014-02-21
2014-02-28
2014-03-07
2014-03-14
2014-03-21
2014-03-28
2014-04-04
2014-04-11
...
相关问题