栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

以迭代方式跳过元素的优雅方式

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

以迭代方式跳过元素的优雅方式

使用

itertools
配方
consume
跳过
n
元素:

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)

注意

islice()
那里的电话;它使用
n, n
,实际上不返回 任何内容 ,并且该
next()
函数返回到默认值。

简化为示例,您要跳过999999个元素,然后返回元素1000000:

return next(islice(permutations(range(10)), 999999, 1000000))

islice()
处理C语言中的迭代器,Python循环无法胜任。

为了说明这一点,以下是每种方法仅重复10次的时间:

>>> from itertools import islice, permutations>>> from timeit import timeit>>> def list_index():...     return list(permutations(range(10)))[999999]... >>> def for_loop():...     p = permutations(range(10))...     for i in xrange(999999): p.next()...     return p.next()... >>> def enumerate_loop():...     p = permutations(range(10))...     for i, element in enumerate(p):...         if i == 999999:...  return element... >>> def islice_next():...     return next(islice(permutations(range(10)), 999999, 1000000))... >>> timeit('f()', 'from __main__ import list_index as f', number=10)5.550895929336548>>> timeit('f()', 'from __main__ import for_loop as f', number=10)1.6166789531707764>>> timeit('f()', 'from __main__ import enumerate_loop as f', number=10)1.2498459815979004>>> timeit('f()', 'from __main__ import islice_next as f', number=10)0.18969106674194336

islice()
方法比下一个最快的方法快近7倍。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387712.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号