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

依然范特西╮ 提交于 2019-12-03 21:07:54

有的时候,我们想基于迭代器的某个特定元素开始进行迭代。也就是说,在这个元素之前的元素都跳过。
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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!