Python:从列表中删除项目直到项目匹配条件的惯用方法?

Kla*_*ven 4 python

刚刚写了这个小帮手,但是我有一种强烈的感觉“应该已经存在”这样的东西。这叫什么?

@listify
def drop_up_to_and_including(l, f):
    """Drops items from a list 'l' up until and including an element `e` is found for which `f(e) == True`

    Example::
    >>> drop_up_to_and_including(range(10), lambda x: x == 5)
    [6, 7, 8, 9]
    """
    found = False
    for e in l:
        if found:
            yield e

        if f(e):
            # note: after yield-statement; so we'll yield starting from the first item _after_ f(e) == True
            found = True
Run Code Online (Sandbox Code Playgroud)

listify做你认为它做的事情:https : //github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149

jof*_*fel 5

您可以使用itertools.dropwhile但需要删除第一个匹配元素并需要反转逻辑:

drop_up_to_and_including = lambda l,f : list(itertools.dropwhile(lambda y: not(f(y)),l))[1:]
Run Code Online (Sandbox Code Playgroud)