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