迭代器迭代 —— itertools.dropwhile

有的时候,我们想基于迭代器的某个特定元素开始进行迭代。也就是说,在这个元素之前的元素都跳过。
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值