0

运行以下代码时,Python2.7 会抛出 NameError。当第二个字典paychecks, 被评估时,就会发生这种情况。第一个 dictemployees很好。

employees = { employee.ID:employee for employee in company.employees }

paychecks = {
    paycheck.ID:paycheck for paycheck in employee.paychecks
    for key, employee in employees
    }

!!! NameError: global name 'employee' is not defined

这是无效的 Python 还是我的代码中的错误?还有什么更好的方法呢?

4

1 回答 1

4

您需要按照嵌套顺序列出循环;你有倒序。您还需要使用该dict.items()方法来生成键值。这有效:

paychecks = {paycheck.ID: paycheck
    for key, employee in employees.items()
    for paycheck in employee.paychecks}

因为您需要在设置employees之前先循环employee

对于 list、dict 和 set 理解,将循环想象为嵌套for语句:

for key, employee in employees.items():
    for paycheck in employee.paychecks:
        paychecks[paycheck.ID] = paycheck

如果您要按照指定的顺序嵌套循环,应该立即清楚为什么会得到 a NameErroron employee

for paycheck in employee.paychecks:
    for key, employee in employees.items():
        paychecks[paycheck.ID] = paycheck

这里外循环试图访问一个不存在的employee对象。

于 2013-12-15T22:33:50.857 回答