Python 2 - > 3:'zip'类型的对象没有len()

Ada*_*tra 39 python-2.7 python-3.x

我正在关注神经网络1的教程

它在Python 2.7中.我正在使用3.4.这是困扰我的路线:

if test_data: n_test = len(test_data)

我明白了:TypeError: object of type 'zip' has no len().

有没有办法重写它,以便它在3.4中工作?

小智 34

现在有点晚了回答,但万一其他人偶然发现它:对于同样的神经网络示例教程,原来我必须在mnist_loader中用一个列表(zip(...))构造包装3个zip调用:

training_data = list(zip(training_inputs, training_results))
(...)
validation_data = list(zip(validation_inputs, va_d[1]))
(...)
test_data = list(zip(test_inputs, te_d[1]))
Run Code Online (Sandbox Code Playgroud)

然后它奏效了.

  • 他们在谈论本教程:http://neuralnetworksanddeeplearning.com/chap1.html (3认同)
  • 晚了,但是欢迎那些晚到的人,ty (2认同)

jfs*_*jfs 32

如果你知道迭代器是有限的:

#NOTE: `sum()` consumes the iterator
n_test = sum(1 for _ in test_data) # find len(iterator)
Run Code Online (Sandbox Code Playgroud)

或者如果你知道它test_data总是很小而且一个分析器说代码是你应用程序的瓶颈,那么这里的代码可能对小代码更有效n_test:

test_data = list(test_data)
n_test = len(test_data)
Run Code Online (Sandbox Code Playgroud)

不幸的是,operator.length_hint()(Python 3.4+)为zip()对象返回零.参见PEP 0424 - 暴露长度提示的方法.

  • 您应该在`if`检查之前执行`test_data = list(test_data)`,否则`if test_data`将始终为true,即使对于空的`zip`也是如此.也可能值得指出`sum(...)`将使用`zip` (2认同)

Ign*_*ams 10

强制zip()评估.

foo = list(zip(...))
Run Code Online (Sandbox Code Playgroud)