首页 > 解决方案 > Python中的生成器,代表无限流

问题描述

我的代码如下:

def infinite_loop():
    li = ['a', 'b', 'c']
    x = 0                           
   
    while True:
        yield li[x]
        if x > len(li):
           x = 0
        else:
           x += 1

我得到一个列表索引超出范围错误。我的代码出了什么问题?

标签: pythonloopsgeneratorindex-error

解决方案


测试以 2 为关闭。最高有效索引是len(li) - 1,因此在使用该索引后,它需要重置为0

def infinite_loop():
    li = ['a', 'b', 'c']
    x = 0                           
   
    while True:
        yield li[x]
        if x == len(li) - 1:
           x = 0
        else:
           x += 1

推荐阅读