Python 来自生成器的列表中项目的意外顺序
下面的代码使用生成器在字符串中创建Python 来自生成器的列表中项目的意外顺序,python,generator,Python,Generator,下面的代码使用生成器在字符串中创建“.的索引列表 def gen(s): dot_index = 0 while dot_index >= 0: dot_index = s.find('.', dot_index + 1) yield dot_index def get_dots(): s = '23.00 98.00 99.00' l = [s.find('.', i + 1) for i in gen(s)] p
“.
的索引列表
def gen(s):
dot_index = 0
while dot_index >= 0:
dot_index = s.find('.', dot_index + 1)
yield dot_index
def get_dots():
s = '23.00 98.00 99.00'
l = [s.find('.', i + 1) for i in gen(s)]
print(l)
get_dots()
我希望列表的顺序是[2,8,14,-1],但实际的顺序是[8,14,-1,2]
请解释为什么第一个索引2是列表中的最后一个
这可能是因为我对发电机的了解不够
谢谢生成器返回您期望的顺序,问题是在
get_dots()
中,您获得第一个点的索引,然后搜索下一个点[s.find('.',i+1)for i in gen(s)]
:
我犯了愚蠢的错误。谢谢。
def gen(s):
dot_index = 0
while dot_index >= 0:
dot_index = s.find('.', dot_index + 1)
yield dot_index
def get_dots():
s = '23.00 98.00 99.00'
l = list(gen(s))
print(l)
get_dots()