是否存在n从迭代器中删除值的pythonic解决方案?您可以通过丢弃n值来执行此操作,如下所示:
def _drop(it, n):
for _ in xrange(n):
it.next()
Run Code Online (Sandbox Code Playgroud)
但是,IMO并不像Python代码那样优雅.我在这里错过了更好的方法吗?
我相信你正在寻找"消费"食谱
http://docs.python.org/library/itertools.html#recipes
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
Run Code Online (Sandbox Code Playgroud)
如果您在不需要特殊的行为n是None,你可以只使用
next(islice(iterator, n, n), None)
Run Code Online (Sandbox Code Playgroud)
您可以创建一个从 element 开始的迭代切片n:
import itertools
def drop(it, n):
return itertools.islice(it, n, None)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1373 次 |
| 最近记录: |