py2 to py3 return iterator

Views And Iterators Instead Of Lists

Some well-known APIs no longer return lists:

  • dict methods dict.keys()dict.items() and dict.values() return “views” instead of lists. For example, this no longer works: d.keys(); k.sort(). Use sorted(d) instead (this works in Python 2.5 too and is just as efficient).

  • Also, the dict.iterkeys()dict.iteritems() and dict.itervalues() methods are no longer supported.

  • map() and filter() return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrap map() in list(), e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

    If the input sequences are not of equal length, map() will stop at the termination of the shortest of the sequences. For full compatibility with map() from Python 2.x, also wrap the sequences initertools.zip_longest(), e.g. map(func, *sequences) becomes list(map(func,itertools.zip_longest(*sequences))).

  • range() now behaves like xrange() used to behave, except it works with values of arbitrary size. The latter no longer exists.

  • zip() now returns an iterator.

posted @ 2017-12-12 10:59  Earendil  阅读(211)  评论(0编辑  收藏  举报