TypeError: object of type 'zip' has no len()、'zip' object is not subscriptable

来源:互联网 发布:网络信息安全措施 编辑:程序博客网 时间:2024/06/04 17:43

笔者遇到的问题:

1.
print(len(training_data))
TypeError: object of type ‘zip’ has no len()

2.
print(training_data[0][0].shape)
TypeError: ‘zip’ object is not subscriptable

笔者各种搜索,然后找到了:

提问者的问题:
Python 2 –> 3: object of type ‘zip’ has no len()
It’s in Python 2.7. I’m using 3.4. This is the line that troubles me:

if test_data: n_test = len(test_data)

I get: TypeError: object of type ‘zip’ has no len().

Is there a way to rewrite it so that it works in 3.4?

回答者的答案之一:
Try using list(zip(…) where you have zip(…) – Julien Jun 27 ‘16 at 4:02

这个来自链接:https://stackoverflow.com/questions/31011631/python-2-3-object-of-type-zip-has-no-len

于是笔者跑去改代码:

把原来的:

    tr_d, va_d, te_d = load_data()    training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]    training_results = [vectorized_result(y) for y in tr_d[1]]    training_data = zip(training_inputs, training_results)    validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]    validation_data = zip(validation_inputs, va_d[1])    test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]    test_data = zip(test_inputs, te_d[1])    return (training_data, validation_data, test_data)

改为了:

    tr_d, va_d, te_d = load_data()    training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]]    training_results = [vectorized_result(y) for y in tr_d[1]]    training_data = list(zip(training_inputs, training_results))    validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]]    validation_data = list(zip(validation_inputs, va_d[1]))    test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]]    test_data = list(zip(test_inputs, te_d[1]))    return (training_data, validation_data, test_data)

然后问题解决了:

不再报错了,运行结果也出来了。

training data<class 'list'>50000(784, 1)(10, 1)
阅读全文
0 0
原创粉丝点击