Python 2 --> 3: object of type 'zip' has no len()

前端 未结 5 646
忘掉有多难
忘掉有多难 2020-12-13 17:38

I\'m following a tutorial on neural nets1

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)

5条回答
  •  孤城傲影
    2020-12-13 18:12

    If you know that the iterator is finite:

    #NOTE: `sum()` consumes the iterator
    n_test = sum(1 for _ in test_data) # find len(iterator)
    

    Or if you know that test_data is always small and a profiler says that the code is the bottleneck in your application then here's code that might be more efficient for small n_test:

    test_data = list(test_data)
    n_test = len(test_data)
    

    Unfortunately, operator.length_hint() (Python 3.4+) returns zero for a zip() object. See PEP 0424 -- A method for exposing a length hint.

提交回复
热议问题