[英]Python yield multiple assignment
I generally try to use yield whenever I can, but I don't get how I'd do it on code like this: 我通常会尽可能地尝试使用yield,但是我不知道如何在这样的代码上使用它:
numbers = [1,2,3,4,5,6,7,8,9,10]
def odd_and_even(numbers):
odd = []
even = []
for number in numbers:
if number % 2:
odd.append(number)
else:
even.append(number)
return (odd, even)
Obviously, in the above case, I could rewrite it as two different functions, but for something more complex, that might be quite computationally expensive because I'd be running twice as many checks. 显然,在上述情况下,我可以将其重写为两个不同的函数,但是对于更复杂的事情,由于我要运行两倍的检查量,因此在计算上可能会非常昂贵。
How could the above code be made to use yield? 上面的代码如何制作为使用yield?
Using partition()
function : 使用
partition()
函数 :
import itertools
def partition(items, predicate=bool):
a, b = itertools.tee((predicate(item), item) for item in items)
return ((item for pred, item in a if not pred),
(item for pred, item in b if pred))
odd, even = partition(numbers, lambda n: n % 2 == 0)
If odd
, even
are not consumed nearly in sync or if the predicate is not expensive then your list version (from the question) should be faster. 如果为
odd
, even
不会同步使用,或者谓词并不昂贵,那么您的列表版本(从问题而来)应该更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.