gpt4 book ai didi

python - Python 生成器表达式中的变量范围

转载 作者:行者123 更新时间:2023-11-28 22:49:20 25 4
gpt4 key购买 nike

我编写了一个函数,它创建一个字典映射字符串 -> 生成器表达式。生成器表达式根据两个条件过滤项目列表,这两个条件对于字典中的每个生成器都是不同的。

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 的最后值进行过滤,大概是因为这两个变量被重新在循环的每次迭代中使用。我该如何解决这个问题?

最佳答案

是的,insttype 名称用作闭包;当您遍历生成器时,它们已绑定(bind)到循环中的最后一个值。

为名称创建一个新的范围;一个函数可以做到这一点:

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}

关于python - Python 生成器表达式中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23940956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com