python - 了解内置的 next() 函数

标签 python

read the documentation在 next() 上,我抽象地理解它。据我了解, next() 用作对可迭代对象的引用,并使 python 依次循环到下一个可迭代对象。说得通!我的问题是,这在内置 for 循环的上下文之外有什么用?什么时候有人需要直接使用 next() ?有人可以提供一个简单的例子吗?谢谢伙伴们!

最佳答案

幸运的是,我昨天写了一篇:

def skip_letters(f, skip=" "):
    """Wrapper function to skip specified characters when encrypting."""
    def func(plain, *args, **kwargs):
        gen = f(p for p in plain if p not in skip, *args, **kwargs)              
        for p in plain:
            if p in skip:
                yield p
            else:
                yield next(gen)
    return func

这使用 next 从生成器函数 f 获取返回值,但穿插有其他值。这允许一些值通过生成器传递,但其他值直接产生。

关于python - 了解内置的 next() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22157807/

相关文章:

Python - 根据计算的百分比返回列表的区域

python 将字符串中编码的 12 位图像转换为 8 位 png

python - 填充二维数组中的边界框

python - 尝试使用 PyOpengl 使用索引和顶点绘制简单的正方形

python - 在图形实现中查找所有循环

python - 登录 Python 脚本不起作用 : results in empty log files

python - 使用 __str__ 打印对象的数组元素

Python 3 线程 websockets 服务器

python - 如何配置 uwsgi 以使用特定版本的 python?

python - 标准化期间屏蔽 0 值