如何移动连续数字的行。 Python 3.3.2

时间:2013-10-14 17:57:09

标签: python python-3.x

我目前正在python 3.3.2中创建日历。现在我有

def month_28():
    if day == 1:
        columns = 7
        for i in range(1, 29):
            if i % columns != 0:
                print(i, end= " ")
                if i <= 9:
                    print(end="    ")
                else:
                   print(end="   ")
            else:
                print(i)

打印

February 2013
Sun   Mon   Tue   Wed   Thu   Fri   Sat
1     2     3     4     5     6     7
8     9     10    11    12    13    14
15    16    17    18    19    20    21
22    23    24    25    26    27    28

但是,如果Jan.在周三结束,我需要2月才能在星期四开始。一直到一年。关于如何将2月1日转移到5个地方并让它在周四开始计算的任何想法?如果有更好的方法来打印一年中每个月连续增加的数字。请告诉我。任何帮助是极大的赞赏。 感谢。

2 个答案:

答案 0 :(得分:2)

您可以使用日历:

>>> import calendar
>>> print calendar.TextCalendar().formatmonth(2013,2,4)
          February 2013
Mon  Tue  Wed  Thu  Fri  Sat  Sun
                      1    2    3
  4    5    6    7    8    9   10
 11   12   13   14   15   16   17
 18   19   20   21   22   23   24
 25   26   27   28

如果您希望星期日作为第一天:

>>> print calendar.TextCalendar(calendar.SUNDAY).formatmonth(2013,2,4)
          February 2013
Sun  Mon  Tue  Wed  Thu  Fri  Sat
                           1    2
  3    4    5    6    7    8    9
 10   11   12   13   14   15   16
 17   18   19   20   21   22   23
 24   25   26   27   28

从概念上讲,日历是一张桌子;表格是列表清单的文字表示:

>>> table=[['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
...        ['','','','','','1','2'],
...        ['3','4','5','6','7','8','9'],
...        ['10','11','12','13','14','15','16'],
...        ['17','18','19','20','21','22','23'],
...        ['24','25','26','27','28','','']] 

如果您想将该表“漂亮地”打印到日历中,则需要自行滚动:

def printTable (tbl, borderHorizontal = '-', borderVertical = '|', borderCross = '+'):
    cols = [list(x) for x in zip(*tbl)]
    lengths = [max(map(len, map(str, col))) for col in cols]
    f = borderVertical + borderVertical.join(' {:>%d} ' % l for l in lengths) + borderVertical
    s = borderCross + borderCross.join(borderHorizontal * (l+2) for l in lengths) + borderCross
    rtr=[s]

    for row in tbl:
        rtr.append(f.format(*row))
        rtr.append(s)

    return '\n'.join(rtr)

print(printTable(table))

打印:

+-----+-----+-----+-----+-----+-----+-----+
| Sun | Mon | Tue | Wed | Thu | Fri | Sat |
+-----+-----+-----+-----+-----+-----+-----+
|     |     |     |     |     |   1 |   2 |
+-----+-----+-----+-----+-----+-----+-----+
|   3 |   4 |   5 |   6 |   7 |   8 |   9 |
+-----+-----+-----+-----+-----+-----+-----+
|  10 |  11 |  12 |  13 |  14 |  15 |  16 |
+-----+-----+-----+-----+-----+-----+-----+
|  17 |  18 |  19 |  20 |  21 |  22 |  23 |
+-----+-----+-----+-----+-----+-----+-----+
|  24 |  25 |  26 |  27 |  28 |     |     |
+-----+-----+-----+-----+-----+-----+-----+

答案 1 :(得分:0)

我知道我没有回答直接问题,但是,你还不想使用calendar模块吗?

无论如何,如果您坚持手动执行,模块datetime的类weekday中的date方法将非常有用。它返回一个从0到6的数字,这正是您需要移动的位数。但是你的双for循环需要工作......