3
考虑以下字符串我可以跳出一个python生成器吗?
long_string = '#' * 4 + 'a' * 10 + '#' * 4
print(long_string)
####aaaaaaaaaa####
我想循环并获得唯一的前几个字符,直到该字符是不一个'#'
我可以遍历并不仅仅是'#'
''.join(x for x in long_string if x.startswith('#'))
'########'
这太多了。
我想要做这样的事情
def gen_break(long_string, mychar):
i = iter(long_string)
s = next(i)
while s == mychar:
yield s
s = next(i)
''.join(gen_break(long_string, '#'))
'####'
该停止迭代时,它遇到了哪些突破的条件。有没有办法在(this for this in that)
语法中更优雅地执行此操作?
注:
这是为了突出我问的问题一个人为的例子。我没有找到解析这个示例字符串的方法。我正在寻找一种以优雅的方式打破迭代的方式,最好使用理解语法。
你不能在基因xp中“突破”。不过,你可以使用'itertools.takewhile'。 – user2357112
[itertools.takewhile](https://docs.python.org/2/library/itertools.html#itertools.takewhile)完全是这样的 – Wondercricket
您可以故意设置您的情况/发生器,以便它精确地导致错误你想突破的点? – toonarmycaptain