简体   繁体   English

如何在 python 中编写“过滤器”生成器?

[英]How do I write a “filter” generator in python?

I'm studying the topic of generators in python and I can't solve an exercise.我正在研究 python 中的生成器主题,但我无法解决一个练习。

I have to write a "filter" generator that takes a predicate and a sequence and produces a sequence that has no elements for which the predicate is true.我必须编写一个“过滤器”生成器,它接受一个谓词和一个序列,并生成一个没有谓词为真的元素的序列。 (similar to the built-in filter function) (类似于内置过滤器功能)

I know how to solve an exercise through a function, but I do not know how to solve it through "yield".我知道如何通过 function 解决一个练习,但我不知道如何通过“yield”解决它。

This is my code:这是我的代码:

def filter(x, lst):
    i = 0
    while i < len(lst):
        if lst[i] != x:
            yield lst[i]
            i += 1
        else:
            continue

I'd be glad to get help with the task.我很乐意在这项任务上得到帮助。

you may use:你可以使用:

def my_filter(pred, seq):
    for item in seq:
        if not pred(item):
            yield item

my_filter generator is iterating over your sequence and when an element applied over the predicate it is False then will yield that element my_filter生成器正在迭代您的序列,并且当应用于谓词的元素为False时,将产生该元素

example:例子:

list(my_filter(lambda x: x >4, [0, 1, 5, 2]))

# [0, 1, 2]

You can use a generator literal to accomplish this in one line您可以使用生成器文字在一行中完成此操作

def my_filter(x, lst):
    yield from (i for i in lst if i != x)

This uses the return keyword instead of yield, but is actually equivalent as it also returns a generator which yields the same items.这使用 return 关键字而不是 yield,但实际上是等效的,因为它还返回一个生成相同项目的生成器。

def my_filter(x, lst):
    return (i for i in lst if i != x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM