简体   繁体   English

我可以用更好的方式编写简单的 Python 代码吗?

[英]Can I write my simple Python code in a better way?

I should rewrite my own function in a better way.我应该以更好的方式重写我自己的函数。 The function takes an iterator and a sequence of boolean functions and returns an iterator of the elements in the input iterator which returns a truthy value.该函数接受一个迭代器和一系列布尔函数,并返回输入迭代器中元素的迭代器,该迭代器返回一个真值。

def allTrue (iterator, funz):
for i in iterator:
    count = 0
    for f in funz:
        if f(i):
            count = count+1
        if count==len(funz):
            yield i

I tried to write this:我试着写这个:

def allTrue2 (iterator, funz):
    return (filter (f , iterator) for f in funz)

But it's wrong.但这是错误的。 How could I improve the code?我怎样才能改进代码?

Output:输出:

print(list(allTrue(range(50),
               (lambda x: x % 3 == 0,
                lambda x: x > 10,
                lambda x: x < 44)
               )))

>>> [12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42]

And if you want a one-liner, just for completeness:如果你想要一个单线,只是为了完整性:

def allTrue (iterator, funz):
    return (i for i in iterator if all(f(i) for f in funz))

Note that this returns a generator, so it has the same effect as using yield .请注意,这将返回一个生成器,因此它与使用yield具有相同的效果。

def allTrue(iterator, funz):
    for i in iterator:
        if all(f(i) for f in funz):
            yield i

You can yield from a generator expression like this:您可以从这样的生成器表达式中产生:

def allTrue(iterator, funz):
    yield from (i for i in iterator if all(f(i) for f in funz))

Keeping things close to your initial approach, you might use a for/else to break once a function returns False and move on to the next element.与最初的方法保持一致,一旦函数返回False并继续下一个元素,您可以使用for/else来中断。 Only if all functions returned True and the loop never broke, the else part will be executed and yield this result:只有当所有函数都返回True并且循环从未中断时,才会执行else部分并yield以下结果:

def allTrue (iterator, funz):
    for i in iterator:
        for f in funz:
            if not f(i):
                break
        else:
            yield i

Regarding your filter approach, you basically created an iterator of iterators.关于您的filter方法,您基本上创建了一个迭代器的迭代器。 You have an iterator filtering the list according to each function separatly .您有一个迭代器根据每个函数单独过滤列表。 You want to filter the list, returning a single iterator, with the condition that all functions return True :您想过滤列表,返回一个迭代器,条件是所有函数都返回True

def allTrue2 (iterator, funz):
    return filter(lambda i: all(f(i) for f in funz), iterator)

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

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