简体   繁体   English

Python:检查嵌套列表中的下一个列表

[英]Python: Check Next List in Nested List

month = [[0,1,0,1,0,1,1], [1,1,1,1,1,1,1], [0,0,0,0,0,0,1], [1,0,0,0,0,0,1]]

each nested list corresponds to a week and each 1 corresponds to an "event" and each event has a random length between 2-14每个嵌套列表对应一个星期,每个1对应一个“事件”,每个事件的长度在 2-14 之间随机
Example:例子:
I want to enter the event at month[0][5] with a length of 6 days how do I make it so that the next 6 days all the "events" (including the events that cross the current week) turn 0?我想在month[0][5]处输入时长为 6 天的事件,如何才能让接下来的 6 天所有“事件”(包括跨越当前周的事件)变为 0?

Expected Output:预计 Output:

month = [[0,1,0,1,0,1,0], [0,0,0,0,0,1,1], [0,0,0,0,0,0,1], [1,0,0,0,0,0,1]]

You can run a nested for loop starting from i = 0 and j =5 and let it run until j = 7 at that point increment i by 1. and loop until you complete iterations equal to the length of the event while replacing the values with 0.您可以从 i = 0 和 j = 5 开始运行嵌套 for 循环,让它运行直到 j = 7,此时 i 递增 1。然后循环直到完成等于事件长度的迭代,同时将值替换为0。

    month[0][5] = 6
    for i in range(0,len(month)):
       for j in range(6,8):
          month[i][j] = 0

here is one way:这是一种方法:

week, day = 0, 5 #starting point eg: month[0][5]
event_days = 6
for _ in range(event_days):
    week, day = (week + 1, 0) if day == len(month[week])-1 else (week, day + 1)
    month[week][day] = 0

output: output:

>>
[
  [0, 1, 0, 1, 0, 1, 0]
, [0, 0, 0, 0, 0, 1, 1]
, [0, 0, 0, 0, 0, 0, 1]
, [1, 0, 0, 0, 0, 0, 1]
]

instead of representing a month as a nested list you could also flatten your month into days.除了将月份表示为嵌套列表之外,您还可以将月份扁平化为几天。 With this list most operations should be much more simple.有了这个列表,大多数操作应该会简单得多。 Whenever needed you can simple select a week by days[7*week:7*(week+1)]无论何时需要,您都可以每周按days[7*week:7*(week+1)]

days = [0,1,0,1,0,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1]

# set an event
event_week = 0
event_day_of_week = 5
event_days = 6

event_begin = 7 * event_week + event_day_of_week + 1
event_end = event_begin + event_days
days[event_begin:event_end] = [0] * event_days

# get a week
week_begin = 1*7
week_end = 2*7
second_week = days[week_begin:week_end]

print(second_week)
>>>[0, 0, 0, 0, 0, 1, 1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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