运行以下代码时,Python2.7会抛出NameError。当第二个字典paychecks
被评估时会发生这种情况。第一个词典employees
很好。
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还是我的代码中的错误?什么是更好的方法呢?
答案 0 :(得分:4)
您需要按照嵌套顺序列出循环;你有倒退的订单。您还需要使用dict.items()
方法生成和两个键值。这有效:
paychecks = {paycheck.ID: paycheck
for key, employee in employees.items()
for paycheck in employee.paychecks}
因为您需要在设置employees
之前首先遍历employee
。
对于list,dict和set comprehensions,将循环描绘为嵌套的for
语句:
for key, employee in employees.items():
for paycheck in employee.paychecks:
paychecks[paycheck.ID] = paycheck
如果您按照指定的顺序嵌套循环,应立即明确为什么在NameError
上获得employee
:
for paycheck in employee.paychecks:
for key, employee in employees.items():
paychecks[paycheck.ID] = paycheck
这里外部循环尝试访问不存在的employee
对象。