调用全局变量时无法解析的引用? - python

我打算在函数“In_queue”中调用两个全局变量(“head”和“tail”),结果成功调用了“head”,但未成功调用“tail”。错误是:

UnboundLocalError: local variable 'tail' referenced before assignment.

在另一个函数“Out_queue”中时,两个变量都成功调用。

代码:

tail = NODE(VALUE())
head = NODE(VALUE())
def In_queue():
    try:
        node = Create_node(*(Get_value()))
    except:
        print("OVERFLOW: No room availible!\n")
        exit(0)
    if not head.nextprt or not tail.nextprt:
        tail.nextprt = head.nextprt = node
    else:
        tail.nextprt = node
        tail = node
    return None
def Out_queue():
    if head.nextprt == tail.nextprt:
        if not head.nextprt:
            print("UNDERFLOW: the queue is empty!\n")
            exit(0)
        else:
            node = head.nextprt
            head.nextprt = tail.nextprt = None
            return node.value
    else:
        node = head.nextprt
        head.nextprt = node.nextprt
        return node.value

参考方案

好吧,那为什么为什么头部工作而尾部却没有呢?正如其他人在评论中提到的那样,将值分配给tail会导致将其视为局部变量。如果是head,您没有分配任何东西,那么解释器会在本地和全局范围内寻找它。为了确保tailhead都可以用作全局变量,您应该使用global tail, head。像这样:

def In_queue():
    global tail, head
    try:
        node = Create_node(*(Get_value()))
    except:
        print("OVERFLOW: No room availible!\n")
        exit(0)
    if not head.nextprt or not tail.nextprt:
        tail.nextprt = head.nextprt = node
    else:
        tail.nextprt = node
        tail = node
    return None

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…

Python:图像处理可产生皱纹纸效果 - python

也许很难描述我的问题。我正在寻找Python中的算法,以在带有某些文本的白色图像上创建皱纹纸效果。我的第一个尝试是在带有文字的图像上添加一些真实的皱纹纸图像(具有透明度)。看起来不错,但副作用是文本没有真正起皱。所以我正在寻找更好的解决方案,有什么想法吗?谢谢 参考方案 除了使用透明性之外,假设您有两张相同尺寸的图像,一张在皱纹纸上明亮,一张在白色背景上有深…

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

Python:无法识别Pip命令 - python

这是我拍摄的屏幕截图。当我尝试在命令提示符下使用pip时,出现以下错误消息:pip无法识别为内部或外部命令,可操作程序或批处理文件。我已经检查了这个线程:How do I install pip on Windows?我所能找到的就是我必须将"C:\PythonX\Scripts"添加到我的类路径中,其中X代表python版本。如您在我的…

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…