2014-03-03 29 views
1

I read the documentation on next()我抽象地理解它。根据我的理解,next()用作对可迭代对象的引用,并将python循环顺序地作为下一个可迭代对象。说得通!我的问题是,除了内建for循环的情况外,这是如何有用的?什么时候有人需要直接使用next()?有人可以提供一个简单的例子吗?谢谢配偶!了解内置next()函数

+0

这似乎是相关的:http://stackoverflow.com/questions/10414210/python-why-should-i-use-next-and-not-obj-next – Dan

+0

这些类型的方法只有在迭代通过列表和只响应指针对象时才有用,因为它知道下一步是什么该列表(或映射)的内存地址是。为了简单访问列表(外部循环),您应该只使用键计数器原理。 – 2014-03-03 21:31:50

回答

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} 
4

由于幸运的是,我昨天一个写道:

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的返回值,但与其他值穿插。这允许一些值通过发生器传递,但是其他值可以直接输出。

1

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