列表理解 - 分配错误之前引用的本地变量

发布于 2025-01-31 01:05:55 字数 1127 浏览 3 评论 0原文

我有一个看起来像这样的图像的源列表(简化为简洁):

images = [
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 1
    },
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 2
    }
]

我正在使用列表理解中的词典理解来删除2个字典项目并构建一个新的清洁词典列表:

images_cleaned = [{k:v for k,v in i.items() if k != 'order' and k != 'type'} for i in images]

然后,我将新列表返回我功能的结束:

return images_cleaned

这是在属性(房地产)列表中,其中包含通过单独请求可用的图像列表。对于25个属性,代码正常运行,但随后我进入了26日,然后以错误的方式行驶:

unboundlocalerror:分配前引用的本地变量'images_cleaned'

但要查看可用于此属性的图像,但并未透露任何不同的内容。它包含相同的图像列表。

我的images_cleaned列表和字典理解有什么明显的错误,这将在返回之前均不会导致分配给images_cleaned变量的后面?我的假设是,即使没有图像,该变量仍然是一个空列表[]

编辑:具体来说,错误发生在返回语句上,返回images_cleaned

I have a source list of images which looks like this (simplified for brevity):

images = [
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 1
    },
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 2
    }
]

And I'm using a dictionary comprehension inside a list comprehension to remove 2 dictionary items and build a new list of cleaned dictionaries:

images_cleaned = [{k:v for k,v in i.items() if k != 'order' and k != 'type'} for i in images]

I then return the new list at the end of my function:

return images_cleaned

This is inside a list of properties (real estate) which contain a list of images available via a separate request. For 25 properties the code works fine, but then I get to the 26th and it trips up with an error:

UnboundLocalError: local variable 'images_cleaned' referenced before assignment

Looking at the images available for this property however, doesn't reveal anything different. It contains the same list of images.

Is there anything noticeably wrong with my images_cleaned list and dictionary comprehension which would result in nothing behind assigned to images_cleaned variable before returning? It's my assumption that even if there were no images then the variable would still be an empty list []?

Edit: Specifically the error occurs on the return statement, returning images_cleaned.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

阪姬 2025-02-07 01:05:55

当我测试时,您现有的代码正常工作,似乎问题在您的代码的另一部分上。 注意:我只是用,

images = [
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 1
    },
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 2
    }
]

def filter_and_clean_image(images):
    images_cleaned = [{k:v for k,v in i.items() if k not in ['order','type']} for i in images]
    return images_cleaned


print(filter_and_clean_image(images))

输出中的替换多重条件检查:

[{'url': 'https://example.com/image.jpg', 'description': 'Caption'}, {'url': 'https://example.com/image.jpg', 'description': 'Caption'}]

您的情况是什么:

此处

当分配发生在函数的身体内的分配之前,在分配发生之前引用了局部变量。当代码试图访问全局变量时,通常会发生错误。由于全局变量具有全局范围,并且可以从程序中的任何地方访问,因此用户通常会尝试在函数中使用全局变量。

在Python中,我们不必在使用该变量之前声明或初始化该变量;默认情况下,始终将变量视为 local 。因此,当程序试图访问函数中的全局变量而不将其指定为全局时,代码将在分配错误之前返回引用的本地变量,因为被引用的变量被视为本地变量。

以下示例代码演示了代码方案,该程序将在其中出现“在分配前引用的本地变量”错误。

count = 10
def myfunc():
    count = count + 1
    print(count)
  
myfunc()

输出:

UnboundLocalError: local variable 'count' referenced before assignment

要解决这一点,我们需要使用全局关键字来解决此错误。下面的示例代码说明了如何使用上述代码方案中的全局关键字解决错误。

count = 10
def myfunc():
    global count
    count = count + 1
    print(count)
  
myfunc()

输出:

11

Your existing code works fine when I tested it, seems the issue is on another part of your code. Note: I just replace multiple condition check with not in,

images = [
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 1
    },
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 2
    }
]

def filter_and_clean_image(images):
    images_cleaned = [{k:v for k,v in i.items() if k not in ['order','type']} for i in images]
    return images_cleaned


print(filter_and_clean_image(images))

Output:

[{'url': 'https://example.com/image.jpg', 'description': 'Caption'}, {'url': 'https://example.com/image.jpg', 'description': 'Caption'}]

What could be your case:

Referenced from here

The local variable referenced before the assignment occurs when some variable is referenced before the assignment within a function’s body. The error usually occurs when the code tries to access the global variable. As the global variables have global scope and can be accessed from anywhere within the program, the user usually tries to use the global variable within a function.

In Python, we do not have to declare or initialized the variable before using it; a variable is always considered local by default. Therefore when the program tries to access the global variable within a function without specifying it as global, the code will return the local variable referenced before the assignment error, since the variable being referenced is considered a local variable.

The below example code demonstrates the code scenario where the program will end up with the “local variable referenced before assignment” error.

count = 10
def myfunc():
    count = count + 1
    print(count)
  
myfunc()

Output:

UnboundLocalError: local variable 'count' referenced before assignment

To fix that, We need to declare the count variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.

count = 10
def myfunc():
    global count
    count = count + 1
    print(count)
  
myfunc()

Output:

11
黎歌 2025-02-07 01:05:55

这是一个属性列表(房地产),其中包含通过单独请求可用的图像列表。

try / dever < / code>块中的“单独请求”是吗?我怀疑第26属性正在提出一个例外,而Images_Cleaned也没有被分配。

This is inside a list of properties (real estate) which contain a list of images available via a separate request.

Is the "separate request" within a try / except block? I suspect the 26th property is raising an Exception and images_cleaned is not getting assigned.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文