繁体   English   中英

如何在 Python 的 for 循环中与前一个变量进行交互?

[英]How to interact with the previous variable in a for loop in Python?

对于 Python 中的 for 循环,我需要一点帮助。 目前,我正在尝试创建一个随机移位生成器,但我还需要对其应用一些规则。 现在,我的 function 随机将班次添加到日历中,但如果最后一班是晚班,我想要添加休息日。 但我不太确定如何与 for 循环中的前一个“i”变量进行交互。 这是我的代码:

# Shift types
shifts = {
    "morning": "9:00 - 17:00",
    "evening": "16:00 - 00:00",
}

day_off = {
    "day off": "X"
}


# Schedule
schedule_ll = {
    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: [],
    27: [],
    28: [],
    29: [],
    30: [],
    31: [],
}

# Function to add shifts to schedule randomly
def start_schedule(schedule, shift, day_off):
    for i in schedule:
        schedule[i].append(random.choice(list(shift.values())))
        if schedule[i-1] == ["16:00 - 00:00"]:
            schedule[i] = list(day_off.values())
    return schedule

print(start_schedule(schedule_ll, shifts, day_off))

因此,当我执行此代码时,我收到 KeyError: 0 错误。 我知道这个错误是由 schedule[i-1] 引起的,但是我不确定如何使它以其他方式工作。 将不胜感激任何帮助!

您可能希望处理循环外的第一个元素,然后只循环剩余的元素。 甚至更简单,只需将您的 if 更改为

if i>1 and schedule[i-1] == ["16:00 - 00:00"]

顺便说一句,请注意您可以使用理解创建字典:

schedule = {k:[] for k in range(1,32)}

两个建议:

  1. 使用.items()字典
  2. 添加逻辑防止尝试访问在调用schedule[i - 1]之前不存在的schedule中的键

这使代码更简洁,防止 function 因关键错误而崩溃,并检查除第一天之外的每一天所需的条件是否成立。

def start_schedule(schedule, shift, day_off):
    for day, list_of_shifts in schedule.items():
        list_of_shifts.append(random.choice(list(shift.values())))
        if (i - 1) in schedule and schedule[i-1] == ["16:00 - 00:00"]:
            schedule[i] = list(day_off.values())
    return schedule

暂无
暂无

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

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