【问题标题】:Can you break out of filter function when certain condition is met? For example I want to break the filter function if x == 237当满足某些条件时,你可以打破过滤功能吗?例如,如果 x == 237 我想打破过滤器功能
【发布时间】:2021-07-01 10:03:04
【问题描述】:
numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527]

print(list(filter(lambda x: (x%2 == 0 or x == 237) , numbers)))
print(list(filter(lambda x: x if x%2 == 0 else x == 237 , numbers)))

【问题讨论】:

  • 也许你可以改用takewhile
  • 你不需要lambdanew_l=[x for x in numbers if x%2==0 or x==237]
  • itertools.takewhile,应该完全符合您的要求。
  • @Sujay:使用列表推导式与跳出循环不同——假设这就是 OP 所说的“跳出过滤功能”。
  • @codingworld:“突破过滤功能”到底是什么意思?

标签: python filter lambda


【解决方案1】:

您可以根据 cmets 中的建议基于 takewhile 编写自己的实现

def take_while(predicate, stop_condition, iterable):
    for x in iterable:
        if predicate(x):
            yield x
        if x == stop_condition:
            break

print(list(take_while(lambda x: x % 2 == 0 or x == 237, 237, numbers)))
print(list(take_while(lambda x: x if x % 2 == 0 else x == 237, 237, numbers)))

输出

[386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918, 237]
[386, 462, 418, 344, 236, 566, 978, 328, 162, 758, 918, 237]

另一种选择是根据数字的索引对列表进行切片

stop_index = numbers.index(237) + 1 if 237 in numbers else len(numbers)
# stop_index = numbers.index(237) + 1
print(list(filter(lambda x: (x % 2 == 0 or x == 237), numbers[:stop_index])))
print(list(filter(lambda x: x if x % 2 == 0 else x == 237, numbers[:stop_index])))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2018-01-02
    • 2017-04-22
    • 2014-12-31
    相关资源
    最近更新 更多