发电机列表中项目的意外顺序



以下代码使用生成器在字符串中创建'.'的索引。

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

最新更新