NameError: ("free variable 'type' referenced before assignment in enclosing scope"[英] NameError: ("free variable 'type' referenced before assignment in enclosing scope"

本文是小编为大家收集整理的关于NameError: ("free variable 'type' referenced before assignment in enclosing scope"的处理方法,想解了NameError: ("free variable 'type' referenced before assignment in enclosing scope"的问题怎么解决?NameError: ("free variable 'type' referenced before assignment in enclosing scope"问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我正在使用此代码

dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) == list else x) for i in range(1, 7)}

列表数据帧转换为数据帧的字典,如本 线程.当我在控制台中使用它时,该行有效,但是当我将它包含在我的脚本中时,我收到以下消息:

NameError: ("free variable 'type' referenced before assignment in enclosing scope", 'occurred at index duration')

在不发布我的整个脚本的情况下,您能否建议我应该寻找导致此错误的内容?脚本中没有使用 type 作为变量,在其他地方也没有使用 x 或 i 作为变量.

Traceback (most recent call last):
  File "C:/PYTHONprojects/DataDump/log_latest_from_api.py", line 138, in main
    dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) is list else x) for i in range(1, 7)}
  File "C:/PYTHONprojects/DataDump/log_latest_from_api.py", line 138, in <dictcomp>
    dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) is list else x) for i in range(1, 7)}
  File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4061, in apply
    return self._apply_standard(f, axis, reduce=reduce)
  File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\frame.py", line 4157, in _apply_standard
    results[i] = func(v)
  File "C:/PYTHONprojects/DataDump/log_latest_from_api.py", line 138, in <lambda>
    dof = {i: dframe.apply(lambda x: x.str[i - 1] if type(x.iat[0]) is list else x) for i in range(1, 7)}
NameError: ("free variable 'type' referenced before assignment in enclosing scope", 'occurred at index duration'

推荐答案

下面是创建此类错误的最小方法:

def foo():
    def bar():
        print(type)

    bar()
    type = 1

foo()

特别是 type = 1 的存在问题,但只有在调用 bar() 之后才会尝试使用它.因此,当您说"在脚本中没有使用 type 作为变量"时,我很难相信这一点.type 在脚本中还有哪些其他提及?您是否为它分配了一个值,将其定义为函数或类的名称,或者在任何地方导入了具有该名称的值?

本文地址:https://www.itbaoku.cn/post/1727780.html