假设我有一个产生值的函数,例如:
import random
def f():
return random.randint(1,10)
在程序的其他地方,我想迭代此函数生成的一系列值:
def g(n):
while True:
if n == k:
return
else:
print("x")
return
使用 while True
语句似乎不太优雅,我更喜欢使用生成器,如下所示:
def f2():
while True:
yield random.randint(1,10)
def g(n):
for k in f2():
if n == k:
return
else:
print("x")
但是,这只是将 while True
的问题插入了 f()
的定义中。是否有一个内置函数接受一个函数并返回一个生成器,如以下伪代码:
def make_generator_from_function(f):
def gen_f():
while True:
yield f()
return gen_f
def g3(n):
for k in make_generator_from_function(f):
if n == k:
return
else:
print("x")
最佳答案
内置iter
函数可以做到这一点:
If the second argument,
sentinel
, is given, thenobject
must be a callable object. The iterator created in this case will callobject
with no arguments for each call to its__next__()
method; if the value returned is equal tosentinel
,StopIteration
will be raised, otherwise the value will be returned.
示例:数字5
是哨兵,因此当random.randint(1, 10)
返回5
时迭代将停止。
>>> import random
>>> def f():
... return random.randint(1, 10)
...
>>> iter(f, 5)
<callable_iterator object at 0x7f3e11becc50>
>>> for x in iter(f, 5):
... print(x)
...
3
3
1
10
9
7
9
6
10
10
9
7
7
3
2
7
2
3
关于python - 是否有一种内置方法可以将无参数函数转换为生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60105793/