具有记忆的迭代器? [英] Iterator with memory?

查看:230
本文介绍了具有记忆的迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on an application which use a markov chain.

此代码的示例如下:

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个最后元素。

What I am looking for is to iterate over train_seq, but to keep the N last elements.

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)

希望我的问题描述足够明确

Hope the description of my problem is clear enough for

推荐答案

窗口会给你 n 一次来自 iterable 的商品。

window will give you n items from iterable at a time.

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

如果您想要前几次相同数量的商品,

If you want the same number of items even the first few times,

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

会这样做。

这篇关于具有记忆的迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆