Files
Python_CookBook_repo/4.迭代器与生成器/8.跳过可迭代对象中的前一部分元素.py
2025-09-10 16:12:45 +08:00

23 lines
1.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from itertools import dropwhile, islice
if __name__ == '__main__':
words = ["#look", "#into", "#my", "eyes", "look", "into", "my", "eyes",
"the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
"eyes", "don't", "look", "around", "the", "eyes", "look", "into",
"my", "eyes", "you're", "under"]
# 想要对可迭代对象进行过滤也可以使用dropwhile函数,比如这里我想过滤掉前几行有#的东西
for i in dropwhile(lambda x : x.startswith('#'), words):
print(i)
# dropwhile会在迭代时对函数进行匹配将符合条件的值丢弃直到出现第一个符合条件的值后停止工作返回所有剩余内容
# 如果你知道需要跳过几个元素那可以直接用islice进行切片操作来过滤
items = ['a', 'b', 'c', 1, 2, 3]
# None表示[3:]
for i in islice(items, 3, None):
print(i)
# 当然,使用列表的过滤方法也可以删除一些不要的东西,但是这样的删除是全局的,而不是仅在开头生效