问题
I am struggling with writing things like this:
list(reversed(list(el.iterancestors()))) + [1,2,3]
Where generators suck, because I am forced to consume the them into lists.
Is there a way to simplify this? I think reversed()
should accept an iterator, am I wrong?
回答1:
Generators are not guaranteed to have a last item, so can't be reversed. What would be the output of the following?
from itertools import cycle
reversed(cycle('abc'))
There is also the risk of accidentally eating all your memory:
from itertools import permutations
reversed(permutations('abcdefghijklmnopqrstuvwxyz', 10)) # 19,275,223,968,000 tuples
Note that the point of reversed()
is to be memory efficient. For sequences, so objects with an index (lists, strings, tuples, ranges), reversed()
produces an iterator that uses an internal index, which starts at len(inputobject) - 1
, and progresses down to 0
as you iterate. It never has to create a copy of the input sequence that way, but that trick can only work on something that already has a length and supports random access.
For your case I'd not use reversed()
anyway. You want a list as output, not a generator, so use slicing to reverse the list instead:
list(el.iterancestors())[::-1] + [1, 2, 3]
Memory efficiency is not an issue here, as you are building a new list object.
来源:https://stackoverflow.com/questions/43511836/why-doesnt-reversed-accept-a-generator