【问题标题】:Understanding builtin next() function了解内置 next() 函数
【发布时间】:2014-04-05 03:40:24
【问题描述】:

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

【问题讨论】:

  • 这些类型的方法仅在您通过列表进行迭代并且仅响应指针对象时才有用,因为它知道该列表(或映射)的下一个内存地址是什么。为了简单地访问一个列表(在循环之外),你应该使用 key-counter 原则。

标签: python


【解决方案1】:

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

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获取返回值,但穿插了其他值。这允许一些值通过生成器传递,但其他值直接产生。

【讨论】:

    【解决方案2】:

    我们可以在很多地方使用next,例如。

    在读取文件时删除标题。

    with open(filename) as f:
        next(f)  #drop the first line
        #now do something with rest of the lines
    

    基于迭代器的zip(seq, seq[1:])实现(来自pairwise recipe iterools):

    from itertools import tee, izip
    it1, it2 = tee(seq)
    next(it2)
    izip(it1, it2)
    

    获取满足条件的第一项:

    next(x for x in seq if x % 100)
    

    使用相邻项作为键值创建字典:

    >>> it = iter(['a', 1, 'b', 2, 'c', '3'])
    >>> {k: next(it) for k in it}
    {'a': 1, 'c': '3', 'b': 2}
    

    【讨论】:

      【解决方案3】:

      next 在许多不同的方面都有用,甚至在 for 循环之外也是如此。例如,如果您有一个可迭代的对象并且您想要第一个满足条件的对象,您可以给它一个generator expression,如下所示:

      >>> lst = [1, 2, 'a', 'b']
      >>> # Get the first item in lst that is a string
      >>> next(x for x in lst if isinstance(x, str))
      'a'
      >>> # Get the fist item in lst that != 1
      >>> lst = [1, 1, 1, 2, 1, 1, 3]
      >>> next(x for x in lst if x != 1)
      2
      >>>
      

      【讨论】:

        猜你喜欢
        • 2014-11-05
        • 1970-01-01
        • 1970-01-01
        • 2012-10-24
        • 2015-10-26
        • 1970-01-01
        • 2011-09-28
        • 1970-01-01
        • 2011-11-11
        相关资源
        最近更新 更多