gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:05:01 24 4
gpt4 key购买 nike

我刚写了这个小 helper ,但我有一种强烈的感觉,这种东西“早该存在”。它叫什么?

@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

最佳答案

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

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

关于Python:从列表中删除项目直到项目符合条件的惯用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33895760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com