已经有Python生成器可以做这些基本的事情了吗?
我发现自己使用这两个自定义生成器并思考“必须有一个 itertools 函数或已经做到这一点的东西!但没有找到任何东西。我错过了什么吗?谢谢!
def gothru(iters):
for i in iters:
for j in i:
yield j
def overnover(fn,startval):
val = startval
while True:
val = fn(val)
yield val
编辑:我后来想象如何overnover
可用于生成斐波那契数列,我意识到需要对其进行泛化以允许该函数具有多个参数,
def overnover(fn,*args):
while True:
args = fn(*args)
return args
然后您可以执行以下操作:
fibInfo = overnover(lambda x,y: (x+y, x), 1, 1)
-> (2,1) ... ( 3、 2) ... (5, 3) ... (8, 5) ... 然后:
fib = imap(lambda x:x[0], fibInfo)
-> 2 ... 3 ... 5 ... 8 ...
谢谢大家!
I found myself using these 2 custom generators and thinking "there's got to be an itertools function or something that already does this! Didn't find any though. Am I missing something? Thanks!
def gothru(iters):
for i in iters:
for j in i:
yield j
def overnover(fn,startval):
val = startval
while True:
val = fn(val)
yield val
EDIT: i was later imagining how overnover
could be used to generate the fibonacci sequence, and i realized that it would need to be generalized to allow the function to have more than one argument
def overnover(fn,*args):
while True:
args = fn(*args)
return args
then you could do:
fibInfo = overnover(lambda x,y: (x+y, x), 1, 1)
-> (2,1) ... (3, 2) ... (5, 3) ... (8, 5) ...
and then:
fib = imap(lambda x:x[0], fibInfo)
-> 2 ... 3 ... 5 ... 8 ...
thanks guys!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第一个是
chain.from_iterable
。与
overnover
最接近的是tabulate
:
这是函数的一种特殊情况,它输出连续的数字。
count
也需要一个step
,因此您可以将其概括为以下是
overnover
的一个版本,它可以让您将值发送到序列中:The first one is
chain.from_iterable
.The closest thing to
overnover
is something liketabulate
:which is a special case of your function where it outputs sequential numbers.
count
also takes astep
, so you could generalize this toHere is a version of
overnover
that would let you send values into the sequence: