码迷,mamicode.com
首页 > 其他好文 > 详细

py2 to py3 return iterator

时间:2017-12-12 12:28:11      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:code   UI   api   range   util   cep   lis   too   map   

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.

py2 to py3 return iterator

标签:code   UI   api   range   util   cep   lis   too   map   

原文地址:http://www.cnblogs.com/earendil/p/8026765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!