列表理解 - 赋值错误之前引用的局部变量

问题描述 投票:0回答:2

我有一个图像源列表,如下所示(为简洁起见,进行了简化):

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
变量?我的假设是,即使没有图像,变量仍然是一个空列表
[]

编辑:具体来说,错误发生在

return
语句上,返回
images_cleaned

python list-comprehension dictionary-comprehension
2个回答
0
投票

当我测试时,您现有的代码工作正常,似乎问题出在代码的另一部分。 注意:我只是将多个条件检查替换为

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))

输出:

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

您的情况可能是什么:

参考自这里

当函数体内的某个变量在赋值之前被引用时,就会出现赋值之前引用的局部变量。当代码尝试访问全局变量时,通常会发生该错误。由于全局变量具有全局作用域并且可以从程序中的任何位置访问,因此用户通常尝试在函数中使用全局变量。

在Python中,我们不必在使用变量之前声明或初始化它;默认情况下,变量始终被视为“本地”。因此,当程序尝试访问函数内的全局变量而不将其指定为全局时,代码将返回赋值错误之前引用的局部变量,因为被引用的变量被视为局部变量。 下面的示例代码演示了程序最终会出现“赋值前引用的局部变量”错误的代码场景。

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

输出:

UnboundLocalError: local variable 'count' referenced before assignment

为了解决这个问题,我们需要使用 global 关键字将 count 变量声明为 
global

来解决此错误。下面的示例代码演示了如何在上述代码场景中使用 global 关键字解决错误。 count = 10 def myfunc(): global count count = count + 1 print(count) myfunc()

输出:

11



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

“单独的请求”是否在
try / except

块内?我怀疑第 26 个属性引发了异常,并且 images_cleaned 没有被分配。

    

© www.soinside.com 2019 - 2024. All rights reserved.