带内存的迭代器?

2024-06-16 10:44:03 发布

您现在位置: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个元素。在

^{pr2}$

希望我的问题描述清楚


Tags: 应用程序示例hellochainforworldisorder
3条回答
seq = [1,2,3,4,5,6,7]
for w in zip(seq, seq[1:]):
  print w

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

^{pr2}$

编辑:但最好使用迭代压缩:

from itertools import izip

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

我用seq是10000000个整数在我的系统上尝试过,结果非常迅速。在

改进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

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)]

如果你想要相同数量的物品,即使是前几次

^{pr2}$

会的。在

相关问题 更多 >