我在python3问题的Python的发电机跃
def generator(string.ascii_lowercase, [0,1,2,3]):
pass
的解决方案应该是:
'a', 'b', 'd', 'g', 'k'
你有一个想法,我怎么能实现这个???
我0,1,2,3
是跳指数
我在python3问题的Python的发电机跃
def generator(string.ascii_lowercase, [0,1,2,3]):
pass
的解决方案应该是:
'a', 'b', 'd', 'g', 'k'
你有一个想法,我怎么能实现这个???
我0,1,2,3
是跳指数
你可以使用一个iterator(迭代器,因为它简化了提前步骤)和嵌套的循环使用next
:
def generator(s, steps):
it = iter(s) # create an iterator over the string
yield next(it) # yield the first item and advance the iterator thereby
for i in steps: # go through the list of steps
for _ in range(i): # advance the iterator by "i" steps without returning
next(it)
yield next(it) # yield again, after the iterator has been advanced.
这给预期的结果:
>>> import string
>>> list(generator(string.ascii_lowercase, [0,1,2,3]))
['a', 'b', 'd', 'g', 'k']
随着itertools.islice
你可以简化和推进下一个项目的收益:
import itertools
def generator(s, steps):
it = iter(s)
yield next(it)
for i in steps:
yield next(itertools.islice(it, i, None))
如果你不喜欢的迭代器您可以随时使用正常的索引(假设你有一个可以索引的顺序 - 一个字符串作品但发电机不会):
def generator(s, steps):
yield s[0]
idx = 1
for i in steps:
idx += i
yield s[idx]
idx += 1
虽然你是正确的@ChristianDean答案不值得下来投票。在这种情况下,简单的评论就足够了。 –
我最近开始使用'collections.deque'与'maxlen = 0'结合'itertools.islice'来消耗迭代。类似[this](https://gist.github.com/juanarrivillaga/087e5a2084b1d9c187c9ca3fb7e294a4) –
@ juanpa.arrivillaga我不知道'deque'在这里会有什么帮助 - 但是'islice'明确地简化了这一点。我已经更新了答案。 – MSeifert
您可以从发布[mcve]开始。你的代码甚至不能在当前状态下工作。 –
@Remolten。这不是代码。这是一个存根和一个要求,而不是一个尝试。 –
堆栈溢出不是代码写入服务。请先尝试解决您自己的问题。如果遇到特定问题,请随时回来询问。 –