【问题标题】:Dictionary not updated after mapping inner function映射内部函数后字典未更新
【发布时间】:2021-05-27 06:21:33
【问题描述】:

我正在尝试使用应用内部函数的映射,以便使用外部函数的局部变量、字典。但是,我无法从内部函数修改字典。这应该是代码:

def outer_func():
    def inner_func(x):
        d[x] = 1
    d = {}
    map(inner_func, [1, 2, 3])
    print(d)

outer_func()

这段代码的输出在python3中是{},而在python2中是{1: 1, 2: 1, 3: 1}。我知道这是范围的问题,然后我尝试在内部函数中使用nonlocal 关键字(使用python3),但这也不起作用。如何使用 map 和内部函数更新 python3 中的 dict?

【问题讨论】:

    标签: python dictionary for-loop scope


    【解决方案1】:

    问题在于 Python 3 中的 map 创建并返回了一个迭代器。您的内部函数没有被调用,因为没有人使用迭代器。如果您在inner_func 中添加了print 语句,您就会看到。

    如果你这样做

    list(map(inner_func, [1, 2, 3]))
    

    你会发现它工作得很好

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      相关资源
      最近更新 更多