python - 使用列表理解生成的函数列表

标签 python list-comprehension

以下 Python 程序打印 13 而不是 7。

increment_by_i = [lambda x: x+i for i in range(10)]
print(increment_by_i[3](4)) 

我不明白以下给出的解释:

This is because the functions created in the loop have the same scope. They use the same variable name, and hence, consequently, all refer to the same variable i, which is 9 at the end of the loop.

  1. 列表推导式如何在列表中创建相应的函数?特别是,它与下面生成 increment_by_i 的代码有何不同?
increment_by_i_modify=[]
for i in range(10): 
    increment_by_i_modify.append(lambda x: x+i)
print(increment_by_i_modify[3](4))
  • 我不明白“它们使用相同的变量名称,因此全部引用相同的变量 i,即循环末尾的 9”这句话。 如果我写
  • test=[i for i in range(10)]
    

    test[3] 是 3 而不是 9。

    最佳答案

    与初始列表理解等效的代码具有相同的行为/输出 如果您进行测试,您将看到 print(increment_by_i_modify[3](4)) 具有相同的输出,13

    您的函数不保留 i 的值,而是保留对 i 的引用,也许以下代码会有所帮助:

    def get_functions():
    
        increment = 0 
        variables = {'i': increment}
    
        my_functions = []
    
        def create_function():
            def f(x):
                return x + variables['i'] 
    
            return f
    
        while increment < 10:
            my_functions.append(create_function())
            variables['i'] = increment
            increment += 1
    
        return my_functions
    
    increment_by_i = get_functions()
    print(increment_by_i_modify[3](4))
    

    输出:

    13
    

    关于python - 使用列表理解生成的函数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57944121/

    相关文章:

    python - 将 where 与 pandas 和分类列一起使用时出错

    python - 如何在列表理解中将变量名称提取为字符串?

    python - Scrapy FakeUserAgentError : Error occurred during getting browser

    python - 使用 OpenCV Python 提取所有边界框

    python - 如何使用 selenium python 替换文本字段中的默认值?

    python - Pandas:返回两个 DataFrame 变量之间匹配值的计数

    python - 如何使用带有条件表达式的 Python 列表理解

    python - 将一个字典的键与另一个字典的键与值列表进行比较

    python - 构建列表列表的字典理解 : referencing the current value for a key during comprehension

    python - 理解嵌套列表理解