这段代码有什么问题?
l = [1,2,3,4,5,6]
for val in iter(l, 4):
print (val)
返回
TypeError: iter(v, w): v must be callable
为什么 callable(list) 返回 True 而 callable(l) 却没有?
编辑 这里应该首选什么方法:
- 手动休息
- 另外一百人
最佳答案
来自 iter
帮助:
iter(...)
iter(collection) -> iterator
iter(callable, sentinel) -> iteratorGet 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
函数的两种变体。第一个接受集合,第二个接受两个参数——函数和标记值。您正在尝试传递集合 和 标记值,这是错误的。
简短说明:您可以从 python 的内置 help
功能中获得很多有趣的信息。只需在 python 的控制台中输入 help(iter)
即可获得有关它的文档。
Why does callabe(list) return true but callable(l) does not?
因为 list
是返回新列表对象的函数。函数是可调用的(这就是函数的作用 - 它被调用),而此函数返回的实例 - 新列表对象 - 不是。
关于python - iter() 是如何工作的,它给出 "TypeError: iter(v, w): v must be callable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19854226/