在发帖之前,我已经阅读了以下内容:模块级变量执行无法访问的问题python 执行命令但我无法让我的代码运行。这是代码:import stringarr = [0, 1, 2, 3, 4]required = 4red = ['0']alpha = string.printable[10:62]ss = ''it = len(arr) - required + 1for i in range(required): now = alpha[i] rd = '-'.join(red) ss += '\t' * (i + 1) + f'for {now} in range({it}-{rd}):\n' red.append(now)exec('def inner_reducer():\n' + ss + '\t' * (required + 1) + f'yield {red[-1]}')a = inner_reducer()print(a.__next__())print(a.__next__())print(a.__next__())print(a.__next__())arr我需要一个以和作为参数的生成器,而不是直接在全局范围内编写required,在分配给生成器后,调用__next__()以生成值。任何帮助都是值得赞赏的。
1 回答
一只萌萌小番薯
TA贡献1795条经验 获得超7个赞
您可以使用工厂函数。例如
import string
def make_inner_reducer_function(arr, required):
red = ['0']
alpha = string.printable[10:62]
ss = ''
it = len(arr) - required + 1
for i in range(required):
now = alpha[i]
rd = '-'.join(red)
ss += '\t' * (i + 1) + f'for {now} in range({it}-{rd}):\n'
red.append(now)
exec('def inner_reducer():\n' + ss + '\t' * (required + 1) + f'yield {red[-1]}')
return locals()['inner_reducer']
f = make_inner_reducer_function([0, 1, 2, 3, 4], 4)
a = f()
print(a.__next__())
print(a.__next__())
print(a.__next__())
print(a.__next__())
添加回答
举报
0/150
提交
取消