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

笔者遇到的问题:

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)
  • 11
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值