gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:34:43 25 4
gpt4 key购买 nike

我目前正在使用 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

但是,如果一月在星期三结束,我需要二月从星期四开始。一路走来,已经一年了。知道如何将 2 月 1 日移至 5 个位置并使其从星期四开始计数吗?如果有更好的方法来打印一年中每个月连续增加的数字。请告诉我。任何帮助是极大的赞赏。谢谢。

最佳答案

您可以只使用日历:

>>> 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 | | |
+-----+-----+-----+-----+-----+-----+-----+

关于python - 如何移动连续数字的行。 Python 3.3.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19366213/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com