Python: 从列表中删除项直到满足条件的惯用方法是什么?

4 投票
2 回答
1023 浏览
提问于 2025-05-11 00:13

我刚写了一个小工具,但我感觉这种东西“应该早就有了”。它叫什么呢?

@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

listify的功能就是你想的那样:https://github.com/shazow/unstdlib.py/blob/master/unstdlib/standard/list_.py#L149

相关文章:

  • 暂无相关问题
暂无标签

2 个回答

0

根据评论的帮助:

>>> drop_up_to_and_including = lambda f, l: list(dropwhile(f, l))[1:]
>>> drop_up_to_and_including(lambda x: x != 5, range(10))
[6, 7, 8, 9]

调整参数的顺序,以便“更贴近常用的写法”,同时支持柯里化。

5

你可以使用 itertools.dropwhile 这个工具,但你需要先去掉第一个符合条件的元素,并且要反转一下逻辑:

drop_up_to_and_including = lambda l,f : list(itertools.dropwhile(lambda y: not(f(y)),l))[1:]

撰写回答