python循环列表(显示工作日的总30天)

list = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]

我想显示工作日的总 30 天,有人可以告诉我如何在 for 或 while 循环中做到这一点吗?谢谢


我想要的输出是:


day 0 : Sun

day 1 : Mon

day 2 : Tue

day 3 : Wed

day 4 : Thu

day 5 : Fri

day 6 : Sat

day 7 : Sun

day 8 : Mon

day 9 : Tue

day 10 : Wed

day 11 : Thu

day 12 : Fri

...

...

day 30 :

我的代码:


     a = 0

     for i in range(0,30):

         print("Day",str(i),list[a])

         a += 1

错误:


    Traceback (most recent call last):

    File "tracker.py", line 25, in <module>

    print("Day",str(i),weekdays[day_number])

    IndexError: list index out of range


慕丝7291255
浏览 196回答 2
2回答

红颜莎娜

monthdays = 30day_index = 6for i in range(monthdays):&nbsp; &nbsp; day_index = (day_index + 1) % 7&nbsp; &nbsp; day = weekdays[day_index]&nbsp; &nbsp; print("day", i, day)day_index 为 6,因为您从星期日开始,但您可以更改它。也不需要调用str(i)inside print,它会为你做。

慕桂英546537

您的问题是您尝试打印weekdays[7]时weekdays只有七个元素(即weekdays[0]to weekdays[6])。有很多方法可以解决这个问题,但在这种情况下,最简单的就是最好的。在您的循环中,使用weekdays[i % len(weekdays)]而不是weekdays[i].模 (mod) 运算符在除其参数时找到产生的余数。这会产生循环行为。n | n % 3 |--+-------+0 |&nbsp; &nbsp;0&nbsp; &nbsp;|&nbsp; 0 = 0 * 3 + [0]1 |&nbsp; &nbsp;1&nbsp; &nbsp;|&nbsp; 1 = 0 * 3 + [1]2 |&nbsp; &nbsp;2&nbsp; &nbsp;|&nbsp; 2 = 0 * 3 + [2]3 |&nbsp; &nbsp;0&nbsp; &nbsp;|&nbsp; 3 = 1 * 3 + [0]4 |&nbsp; &nbsp;1&nbsp; &nbsp;|&nbsp; 4 = 1 * 3 + [1]5 |&nbsp; &nbsp;2&nbsp; &nbsp;|6 |&nbsp; &nbsp;0&nbsp; &nbsp;|7 |&nbsp; &nbsp;1&nbsp; &nbsp;|8 |&nbsp; &nbsp;2&nbsp; &nbsp;|9 |&nbsp; &nbsp;0&nbsp; &nbsp;|因此,当您到达超过 长度的some_list索引时,索引i % len(some_list)将循环回 0 并让您继续前进。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python