python - iter() 是如何工作的,它给出 "TypeError: iter(v, w): v must be callable"

标签 python python-3.x iterator typeerror

这段代码有什么问题?

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) 返回 Truecallable(l) 却没有?

编辑 这里应该首选什么方法:

  1. 手动休息
  2. 另外一百人

最佳答案

来自 iter 帮助:

iter(...)
iter(collection) -> iterator
iter(callable, sentinel) -> iterator

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 函数的两种变体。第一个接受集合,第二个接受两个参数——函数和标记值。您正在尝试传递集合 标记值,这是错误的。

简短说明:您可以从 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/

相关文章:

python - 检查列表中的任何点是否位于两个固定点 A 和 B 之间的最快方法

python - 如何通过字符串将 pandas 数据框分割成 block ?

python - 如何将 Pandas 对象而不是整个数据帧转换为字符串?

c++ - 基于上下文的 partition_copy

c++ - 如何编写可与 STL 算法一起使用的随机访问自定义迭代器?

python Tkinter() 如何隐藏用户界面

python - 如何从另一个数据帧为一个数据帧分配特定值?

python - 使用 bool 掩码从两个较小的张量创建 TensorFlow 张量

python - Python Bot 中的子命令

file - 为什么 File::bytes 以不同于 hexdump 的顺序遍历字节?