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]]
每个嵌套列表对应一周和
每个 1
对应一个“事件”,每个事件的长度在 2-14
之间随机
示例:
我想在 month[0][5]
参加为期 6 天的活动
我如何才能让接下来的 6 天所有“事件”(包括跨越当前周的事件)变为 0?
预期输出:
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]]
您可以 运行 一个嵌套的 for 循环,从 i = 0 和 j =5 开始,让它 运行 直到 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
这是一种方法:
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
输出:
>>
[
[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]
]
除了将月份表示为嵌套列表之外,您还可以将月份扁平化为几天。有了这个列表,大多数操作应该会简单得多。无论何时需要,您都可以每周 select 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]
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]]
每个嵌套列表对应一周和
每个 1
对应一个“事件”,每个事件的长度在 2-14
之间随机
示例:
我想在 month[0][5]
参加为期 6 天的活动
我如何才能让接下来的 6 天所有“事件”(包括跨越当前周的事件)变为 0?
预期输出:
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]]
您可以 运行 一个嵌套的 for 循环,从 i = 0 和 j =5 开始,让它 运行 直到 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
这是一种方法:
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
输出:
>>
[
[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]
]
除了将月份表示为嵌套列表之外,您还可以将月份扁平化为几天。有了这个列表,大多数操作应该会简单得多。无论何时需要,您都可以每周 select 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]