python - 从python中的迭代对象创建一个带有一组树的迭代对象

标签 python python-3.x

如何从迭代对象创建迭代组的三个?为了创建一对迭代函数,我可以做类似的事情 从 itertools 导入 tee

def func(iterate):
    i, j = tee(iterate)
    next(j, None)
    return zip(i, j)

l = [1,2,3,4,5]
for a, b in func(l):
    print(a, b)
> 1, 2
> 2, 3
> 3, 4
> 4, 5

最佳答案

您可以扩展您已经为两人一组所做的工作,但为第三项增加一个变量:

def func(iterate):
    i, j, k = tee(iterate, 3)
    next(j, None)
    next(k, None)
    next(k, None)
    return zip(i, j, k)

l = [1,2,3,4,5]
for a, b, c in func(l):
    print(a, b, c)

这个输出:

1 2 3
2 3 4
3 4 5

请注意,问题中的示例代码不正确,因为它在 func 的返回值中缺少对 zip 的调用。

关于python - 从python中的迭代对象创建一个带有一组树的迭代对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55214404/

相关文章:

python - 如何序列化作为 XML Exporter 中的项目列表的 Scrapy 字段

python - 将嵌套列表写入 .txt 文件

python - python中没有最后4个字节的二进制数据的CRC32

带有可变参数的 Python "maximum recursion depth exceeded in comparison"。但是,可以很好地处理列表

python - 将列添加到稀疏矩阵

python - 计算 python/pandas 中组的平均值

python - 将参数传递给父类(super class)时,错误标志为 : "module.__init__() takes at most 2 arguments (3 given)"?

python - Python 3.8 中 pyFFTW (scipy.fftpack) 导入错误

Python 以特定顺序生成子列表 - itertools?

python - 为什么属性装饰器显示 "object has no attribute"?