gpt4 book ai didi

python - 使用嵌套生成器 pickle 对象

转载 作者:行者123 更新时间:2023-12-01 08:17:27 25 4
gpt4 key购买 nike

假设我有一个任意嵌套的列表,其中一些嵌套元素可以是生成器。例如:

nested_gens = [
[1, [2, [3, 4]]],
[2, (map(int, '123'))],
[3, (map(str, range(i+1)) for i in range(2))],
{'a': ({k: (float(i) for i in range(2))} for k in 'xyz')},
{'b': {'c': dict(zip(range(3), 'abc'))}}
]

我如何递归地遍历这个结构并消耗所有生成器对象以便可以对它们进行 pickle ?

我想要的输出是:

[
[1, [2, [3, 4]]],
[2, [1, 2, 3]],
[3, [['0'], ['0', '1']]],
{'a': [{'x': [0.0, 1.0]}, {'y': [0.0, 1.0]}, {'z': [0.0, 1.0]}]},
{'b': {'c': {0: 'a', 1: 'b', 2: 'c'}}}
]
<小时/>

这个问题的解决方案可以推广到 pickle 包含生成器的对象。我找到的所有处理 TypeError: can't pickle Generator objects 的答案都不处理嵌套生成器。

更新:该解决方案应该能够处理任何类型的嵌套元素。

最佳答案

一种方法是递归地遍历嵌套对象并将生成器转换为列表

from inspect import isgenerator, isgeneratorfunction

def consume_all_generators(row):

if isinstance(row, str):
return row
elif isinstance(row, dict):
return {k: consume_all_generators(v) for k, v in row.items()}

output = []
try:
for val in row:
if isgenerator(val) or isgeneratorfunction(val):
output.append(list(consume_all_generators(val)))
else:
output.append(consume_all_generators(val))
return output
except TypeError:
return row

将此应用于问题中的示例:

print(consume_all_generators(nested_gens))
#[[1, [2, [3, 4]]],
# [2, [1, 2, 3]],
# [3, [['0'], ['0', '1']]],
# {'a': [{'x': [0.0, 1.0]}, {'y': [0.0, 1.0]}, {'z': [0.0, 1.0]}]},
# {'b': {'c': {0: 'a', 1: 'b', 2: 'c'}}}]

关于python - 使用嵌套生成器 pickle 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54897534/

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