2014-03-03 30 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 
>>>