Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中元组中的迭代生成器_Python_Generator_Lazy Evaluation - Fatal编程技术网

python中元组中的迭代生成器

python中元组中的迭代生成器,python,generator,lazy-evaluation,Python,Generator,Lazy Evaluation,假设我有一张单子 xs = [0,1,2,3] [some_function(current, next) for current, next in zip(xs, xs[1:])] 我想迭代这个列表的对(当前,下一个)。要澄清zip创建列表[(0,1)、(1,2)、(2,3)] 问题是,如果xs是一个生成器而不是一个列表,那么要用zip实现这一点,我需要从中创建一个列表,这肯定不是最佳解决方案。这在无限迭代器等情况下有效 def pairwise(iterator): """Iter

假设我有一张单子

xs = [0,1,2,3]
[some_function(current, next) for current, next in zip(xs, xs[1:])]
我想迭代这个列表的对(当前,下一个)。要澄清zip创建列表[(0,1)、(1,2)、(2,3)]


问题是,如果xs是一个生成器而不是一个列表,那么要用zip实现这一点,我需要从中创建一个列表,这肯定不是最佳解决方案。

这在无限迭代器等情况下有效

def pairwise(iterator):
    """Iterate over pairs of an iterator."""
    last = next(iterator)
    while True:
        this = next(iterator)
        yield last, this
        last = this

您可以首先将迭代器转换为列表(如果您确定迭代器不能是无限的):

可以使用从一个迭代器创建多个独立迭代器的

my_iter, next_iter = tee(myiter)
next(nextiter)

[some_function(current, ne) for current, ne in zip(myiter, nextiter)]

在这种情况下,这可能会起作用,但是无限迭代器呢?他说他知道他可以做到这一点。他说这肯定不是最佳解决方案。尽管提议的dupe说它的输入是一个列表,这说明输入不是一个列表,但使用
itertools.tee
的答案是一样的。Neat,我不知道existedI考虑过这一点,但如果需要三元组的itertate,这将稍微复杂一些,大小为n的元组等@user1685095然后您可以使用
deque
,并将
maxsize
设置为n。但是用另一个答案,我不知道
itertools.tee
my_iter, next_iter = tee(myiter)
next(nextiter)

[some_function(current, ne) for current, ne in zip(myiter, nextiter)]