问题描述
我正在努力写这样的东西:
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.
有没有一种方法可以简化这一过程?我认为reversed()
应该接受迭代器,对吗?
Is there a way to simplify this? I think reversed()
should accept an iterator, am I wrong?
推荐答案
不能保证生成器具有最后一项,因此不能反转.以下内容的输出是什么?
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
请注意,reversed()
的点将是内存有效的.对于序列,因此具有索引(列表,字符串,元组,范围)的对象,reversed()
会生成一个使用内部索引的迭代器,该内部索引从len(inputobject) - 1
开始,并在进行迭代时向下扩展到0
.它永远不必以这种方式创建输入序列的副本,但是该技巧只能在已经具有一定长度并支持随机访问的对象上起作用.
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.
对于您的情况,我还是不会使用reversed()
.您希望将列表作为输出而不是生成器,因此请使用切片来反转列表:
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.
这篇关于为什么reversed()不接受生成器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!