How to store itertools.chain and use it more than once?

拈花ヽ惹草 提交于 2019-12-19 06:30:54

问题


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?


回答1:


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.

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.




回答2:


Try itertools.tee:

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


来源:https://stackoverflow.com/questions/13156518/how-to-store-itertools-chain-and-use-it-more-than-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!