new*_*kid 9 python iterator typeerror python-3.x
这段代码有什么问题?
l = [1,2,3,4,5,6]
for val in iter(l, 4):
print (val)
Run Code Online (Sandbox Code Playgroud)
它回来了
TypeError: iter(v, w): v must be callable
Run Code Online (Sandbox Code Playgroud)
为什么callable(list)返回True但可调用(l)不是?
编辑 这里应该首选哪种方法:
来自iter帮助:
iter(...)
iter(collection) - > iterator
iter(callable,sentinel) - > iteratorRun Code Online (Sandbox Code Playgroud)Get an iterator from an object. In the first form, the argument must supply its own iterator, or be a sequence. In the second form, the callable is called until it returns the sentinel.
您正在混合两种iter功能变体.第一个接受集合,第二个接受两个参数 - 函数和sentinel值.你试图传递集合和哨兵值,这是错误的.
简短说明:你可以从python的内置help函数中获得很多有趣的信息.只需输入python的控制台help(iter),您就可以获得文档.
为什么callabe(list)返回true但是callable(l)不返回?
因为list是返回新列表对象的函数.函数是可调用的(这是函数的作用 - 它被调用),而这个函数返回的实例 - 新的列表对象 - 不是.
当使用两个参数iter调用时,采用可调用值和标记值.它的行为就像它实现的那样:
def iter2args(f, sentinel):
value = f()
while value != sentinel:
yield value
value = f()
Run Code Online (Sandbox Code Playgroud)
传入的内容f必须是可调用的,这意味着您可以像函数一样调用它.该list内置是一个type对象,你用它来创建新的列表实例,通过调用它像一个函数:
>>> list('abcde')
['a', 'b', 'c', 'd', 'e']
Run Code Online (Sandbox Code Playgroud)
l您传入的列表是现有的列表实例,不能像函数一样使用:
>>> l = [1,2,3,4,5,6]
>>> l(3)
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
l(3)
TypeError: 'list' object is not callable
Run Code Online (Sandbox Code Playgroud)
因此,list类型对象和列表实例之间存在巨大而重要的差异,这在使用时会显示出来iter.
要遍历列表直到到达哨兵,您可以使用itertools.takewhile:
import itertools
for val in itertools.takewhile(l, lambda x: x!= 4):
print(val)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4638 次 |
| 最近记录: |