Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 来自生成器的列表中项目的意外顺序_Python_Generator - Fatal编程技术网

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()