我通过循环遍历源列表来构建列表。 如果我遇到特定值,我想跳过它以及列表中的下一个n项。
有没有更好的方法来编写下面的process_things函数?
def test_skip(thing):
return thing == 'b'
def num_to_skip(thing):
return 3
def process_things(things):
"""
build list from things where we skip every test_skip() and the next num_to_skip() items
"""
result = []
skip_count = 0
for thing in things:
if test_skip(thing):
skip_count = num_to_skip(thing)
if skip_count > 0:
skip_count -= 1
continue
result.append(thing)
return result
source = list('abzzazyabyyab')
intended_result = list('aazyaa')
assert process_things(source) == intended_result
答案 0 :(得分:4)
您可以使用迭代器和itertools
中的consume
食谱。致电consume(iterator, n)
推进iterator
个n
个项目。如果在for循环遍历迭代器时调用它,则下一次迭代将从第一个consume
没有消耗的项开始。
import collections
from itertools import islice
def consume(iterator, n):
"Advance the iterator n-steps ahead. If n is none, consume entirely."
# Use functions that consume iterators at C speed.
if n is None:
# feed the entire iterator into a zero-length deque
collections.deque(iterator, maxlen=0)
else:
# advance to the empty slice starting at position n
next(islice(iterator, n, n), None)
def process_things(things):
"""
build list from things where we skip every test_skip() and the next num_to_skip() items
"""
result = []
things = iter(things)
for thing in things:
if test_skip(thing):
consume(things, num_to_skip(thing) - 1)
else:
result.append(thing)
return result
请注意我写的process_things
的方式,当它遇到test_skip
要跳过的项目时,它会计算要跳过的num_to_skip(thing)
项目中的项目。这与您的代码所做的相符,但它与您的描述完全匹配,后者表示"跳过它以及列表中的下n个项目"。