Views And Iterators Instead Of Lists
Some well-known APIs no longer return lists:
dict
methodsdict.keys()
,dict.items()
anddict.values()
return “views” instead of lists. For example, this no longer works:k = d.keys(); k.sort()
. Usek = sorted(d)
instead (this works in Python 2.5 too and is just as efficient).- Also, the
dict.iterkeys()
,dict.iteritems()
anddict.itervalues()
methods are no longer supported. map()
andfilter()
return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrapmap()
inlist()
, e.g.list(map(...))
, but a better fix is often to use a list comprehension (especially when the original code useslambda
), or rewriting the code so it doesn’t need a list at all. Particularly tricky ismap()
invoked for the side effects of the function; the correct transformation is to use a regularfor
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 withmap()
from Python 2.x, also wrap the sequences initertools.zip_longest()
, e.g.map(func, *sequences)
becomeslist(map(func,itertools.zip_longest(*sequences)))
.range()
now behaves likexrange()
used to behave, except it works with values of arbitrary size. The latter no longer exists.zip()
now returns an iterator.
时间: 2024-11-14 12:23:48