I read the documentation on next()我抽象地理解它。根據我的理解,next()用作對可迭代對象的引用,並將python循環順序地作爲下一個可迭代對象。說得通!我的問題是,除了內建for循環的情況外,這是如何有用的?什麼時候有人需要直接使用next()?有人可以提供一個簡單的例子嗎?謝謝配偶!瞭解內置next()函數
1
A
回答
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
>>>
相關問題
- 1. 瞭解ç內置庫函數實現
- 2. 的.next()函數
- 3. 瞭解內部函數在Javascript
- 4. 瞭解JavaScript函數和插件設置
- 5. 瞭解lambda函數
- 6. 瞭解set()函數
- 7. 瞭解PHP函數
- 8. 瞭解printf函數
- 9. 瞭解atoi()函數
- 10. 瞭解lambda函數
- 11. 瞭解JavaScript函數
- 12. 瞭解JavaScript函數
- 13. 內置函數中發生了什麼?
- 14. 瞭解分解函數
- 15. jQuery的幫助,next()函數
- 16. Python的__iter__和next()函數
- 17. jquery .next()函數不工作
- 18. jquery next()函數不工作
- 19. 試圖瞭解此函數:Array.prototype.reverse =函數(){
- 20. 瞭解遞歸函數python
- 21. 瞭解scala的Vs函數
- 22. 瞭解Azure函數行爲
- 23. SQL Server:瞭解DATEDIFF函數
- 24. 瞭解c函數指針
- 25. 需要了解Javascript函數
- 26. 瞭解JavaScript函數範圍
- 27. 瞭解函數指針
- 28. 瞭解遞歸函數
- 29. Ocaml,瞭解一個函數
- 30. 瞭解MCPL函數調用
這似乎是相關的:http://stackoverflow.com/questions/10414210/python-why-should-i-use-next-and-not-obj-next – Dan
這些類型的方法只有在迭代通過列表和只響應指針對象時纔有用,因爲它知道下一步是什麼該列表(或映射)的內存地址是。爲了簡單訪問列表(外部循環),您應該只使用鍵計數器原理。 – 2014-03-03 21:31:50