[PythonCookBook][迭代器和生成器] 如何跳过迭代器的前几个元素

目的

在下列文件的内容中,我们希望将以#号开头的几个元素略过,然后继续打印

被测试对象

#aaa
#bbb
#ccc
#ddd
python a
python b
eee
fff
ggg
python x

解决方案1

使用dropwhile方法,可以将符合条件的条目略过。
其中dropwhile方法需要输入一个判断函数和一个可迭代对象。

from itertools import dropwhile

with open('test') as f:
    for line in dropwhile(lambda line:line.startswith('#'), f):
        print(line, end='')

解决方案1的结果

python a
python b
eee
fff
ggg
python x
Process finished with exit code 0

解决方案2

如果知道需要跳过几个元素,则使用islice方法精准过滤

from itertools import islice

items = ['a','b','c','d','e','f']
for i in islice(items, 2, None):
    print(i)

解决方案2的结果

d
e
f

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/qq_33868661/article/details/114975040