本文介绍了如何存储itertools.chain并多次使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用itertools.chain进行列表的有效串联(记忆化),但是我需要能够多次读取(或map等)结果.此示例说明了问题:

I would like to use itertools.chain for efficient concatenation of lists (memoization), but I need to be able to read (or map, etc.) the result multiple times. This example illustrates the problem:

import itertools
a = itertools.chain([1, 2], [3, 4])
print list(a) # => [1, 2, 3, 4]
print list(a) # => []

避免此问题的最佳方法是什么?

What is the best way to avoid this problem?

推荐答案

与所有生成器一样,您需要将其转换为列表并存储该结果:

As with all generators, you'll need to convert it to a list and store that result instead:

a = list(a)

这是生成器的基本原理,希望它们仅一次产生它们的序列.

This is a fundamental principle of generators, they are expected to produce their sequence only once.

此外,您不能简单地存储用于生成备忘录的生成器,因为基础列表可能会更改.在几乎所有的备忘录用例中,您都应该存储列表.生成器通常仅是有效转换或过滤基础序列的一种手段,并不代表您想要记忆的数据.就像您要存储一个函数,而不是它的输出一样.在您的特定情况下,如果您所做的只是使用chain()连接现有列表,请直接存储这些列表.

Moreover, you cannot simply store a generator for memoization purposes, as the underlying lists could change. In almost all memoization use-cases, you should store the list instead; a generator is usually only a means of efficiently transforming or filtering the underlying sequences, and does not represent the data you want to memoize itself. It's as if you are storing a function, not it's output. In your specific case, if all what you are doing is using chain() to concatenate existing lists, store those lists directly instead.

请注意,这使生成器可以产生无穷的序列,因此请小心转换为列表.

Note that this enables generators to produce endless sequences, so be careful with that you convert to a list.

这篇关于如何存储itertools.chain并多次使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:34