Python生成器表达式中的变量作用域

2 投票
1 回答
2393 浏览
提问于 2025-04-18 07:58

我写了一个函数,这个函数创建了一个字典,字典的内容是字符串和生成器表达式的对应关系。这个生成器表达式会根据两个标准来过滤一组项目,而这两个标准对于字典中的每个生成器都是不同的。

def iters(types):
    iterators = {}
    for tname in types:
        inst, type = tname.split('|')
        iterators[tname] = (t for t in transactions() if t['institution_type'] == inst and t['type'] == type)
    return iterators

我遇到的问题是,所有的生成器都是根据最后一次循环中insttype的值来过滤的,可能是因为这两个变量在循环的每次迭代中都被重复使用了。我该如何解决这个问题呢?

1 个回答

4

是的,insttype 这两个名字是用作 闭包 的;当你在循环遍历生成器的时候,这些名字会绑定到循环中的最后一个值。

可以为这些名字创建一个新的作用域;一个函数可以做到这一点:

def iters(types):
    def build_gen(tname):
        inst, type = tname.split('|')
        return (t for t in transactions()
                if t['institution_type'] == inst and t['type'] == type)
    iterators = {}
    for tname in types:
        iterators[tname] = build_gen(tname)
    return iterators

你也可以用字典推导式来替换最后几行代码:

def iters(types):
    def build_gen(tname):
        inst, type = tname.split('|')
        return (t for t in transactions() 
                if t['institution_type'] == inst and t['type'] == type)
    return {tname: build_gen(tname) for tname in types}

撰写回答