gpt4 book ai didi

带内存的迭代器?

转载 作者:行者123 更新时间:2023-11-28 20:52:16 26 4
gpt4 key购买 nike

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

此代码的示例如下:

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)

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

最佳答案

window 将一次为您提供 iterable 中的 n 项。

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

会那样做。

关于带内存的迭代器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7113724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com