python - Python中的生成器,代表无限流
问题描述
我的代码如下:
def infinite_loop():
li = ['a', 'b', 'c']
x = 0
while True:
yield li[x]
if x > len(li):
x = 0
else:
x += 1
我得到一个列表索引超出范围错误。我的代码出了什么问题?
解决方案
测试以 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
推荐阅读
- c - 将 int 分配给数组时出现分段错误
- url - 制作一个重定向到您上次打开的 IE 页面的 URL?
- java - 如何在 Rally 的 java 中查询从故事定义到完成的总花费时间?
- android - 从 Kotlin 中的片段获取用户在 AlertDialog 上的输入
- mysql - How to extract hour from timestamp?
- swiftui - 如何在 SwiftUI 中比较两个形状?
- dulwich - 德威瓷器 - 重置本地存储库
- php - CORS 块 Laravel + VueJS Axios
- java - 数据结构最适合像 Item can not be Shipping to a specific postalCode 这样的规则
- unity3d - 如何使用 IronSource Unity 设置 SetAdvertiserTrackingEnabled?