具有记忆的迭代器?

时间:2011-08-18 20:28:48

标签: iterator python

我正在开发一个使用马尔可夫链的应用程序。

此代码的示例如下:

chain = MarkovChain(order=1)
train_seq = ["","hello","this","is","a","beautiful","world"]

for i, word in enum(train_seq):
 chain.train(previous_state=train_seq[i-1],next_state=word)

我正在寻找的是迭代train_seq,但保留N个最后元素。

for states in unknown(train_seq,order=1):
 # states should be a list of states, with states[-1] the newest word,
 # and states[:-1] should be the previous occurrences of the iteration.
 chain.train(*states)

希望我的问题描述足够清楚

3 个答案:

答案 0 :(得分:6)

window会一次从n为您提供iterable项。

from collections import deque

def window(iterable, n=3):
    it = iter(iterable)
    d = deque(maxlen = n)
    for elem in it:
        d.append(elem)
        yield tuple(d)


print [x for x in window([1, 2, 3, 4, 5])]
# [(1,), (1, 2), (1, 2, 3), (2, 3, 4), (3, 4, 5)]

如果您想要前几次使用相同数量的物品,

from collections import deque
from itertools import islice

def window(iterable, n=3):
    it = iter(iterable)
    d = deque((next(it) for Null in range(n-1)), n)
    for elem in it:
        d.append(elem)
        yield tuple(d)


print [x for x in window([1, 2, 3, 4, 5])]

会这样做。

答案 1 :(得分:1)

seq = [1,2,3,4,5,6,7]
for w in zip(seq, seq[1:]):
  print w

您还可以执行以下操作来创建任意大小的对:

tuple_size = 2
for w in zip(*(seq[i:] for i in range(tuple_size)))
  print w

编辑:但是使用迭代zip可能更好:

from itertools import izip

tuple_size = 4
for w in izip(*(seq[i:] for i in range(tuple_size)))
  print w

我在我的系统上尝试了这个,seq是10,000,000个整数,结果很快。

答案 2 :(得分:0)

改善yan的回答以避免副本:

from itertools import *

def staggered_iterators(sequence, count):
  iterator = iter(sequence)
  for i in xrange(count):
    result, iterator = tee(iterator)
    yield result
    next(iterator)

tuple_size = 4
for w in izip(*(i for i in takewhile(staggered_iterators(seq, order)))):
  print w