简体   繁体   中英

Python, alternate list by index

I have a problem about a python system that has a schedule of 7 days, each day is the index of this list. The problem is that we have a 24 hours schedule, so each week schedule should alternate like in the picture. One of the rule is that the first week on range always finish on the 6 (Sunday), and the end date of the week can finish in any day.

Maybe I'm seeing this in a harder way that it really is. I hope some help. Thanks in advance.

在此处输入图片说明

Check whether the iteration variable is even or odd, and append the appropriate list to the result.

result = []
for i in range(5):
    if i % 2 == 0: 
        result += list(range(7))
    else:
        result += list(range(1, 7)) + [1]
print(result)

Something like this works:

days = 7 
weeks = 4
schedule = [(d+ w%2)%days + int((d+w%2)>(days-1)) for w in range(weeks) for d in range(days)]`

Which essentially says that if it's an odd week (w%2 = 1) add one to the normal schedule and don't allow the final day to be equal to 0, which is why I add the int((d+w%2)>(days-1)) term.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM