码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器迭代的时候跳过第一部分

时间:2019-11-06 22:58:04      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:itertools   方法   use   war   dir   with   out   就是   provided   

有的时候,我们想基于迭代器的某个特定元素开始进行迭代。也就是说,在这个元素之前的元素都跳过。
itertools提供了一个dropwhile方法:
itertools.dropwhile(predicate, iterable)
Make an iterator that drops elements from the iterable as long as the predicate is true; afterwards, returns every element. Note, the iterator does not produce any output until the predicate first becomes false, so it may have a lengthy start-up time.
翻译即为:iterable中的每个元素从index 0开始,依次通过predicate函数进行检查,当predicate的结果为true时,跳过,直到第一次遇到为false的情况。从第一个为false的元素开始,后面的元素全部返回。
示例如下:

with open('/etc/passwd') as f:
    for line in f:
        print(line, end='')

##
# User Database
#
# Note that this file is consulted directly only when the system is running 
# in single-user mode. At other times, this information is provided by
# Open Directory.
...
##
nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false 
root:*:0:0:System Administrator:/var/root:/bin/sh

假如现在要过滤掉所有的注释内容,则可以编写如下代码:

from itertools import dropwhile
with open('/etc/passwd') as f:
    for line in dropwhile(lambda line: line.startswith('#'), f):
        print(line, end='')

nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false 
root:*:0:0:System Administrator:/var/root:/bin/sh

迭代器迭代的时候跳过第一部分

标签:itertools   方法   use   war   dir   with   out   就是   provided   

原文地址:https://www.cnblogs.com/jeffrey-yang/p/11809061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!