Skip to main content
 首页 » 编程设计

python之如何使用 iter 函数循环遍历列表,直到找到某个匹配项

2025年05月04日11zhwl

<分区>

坦率地说,我不明白如何使用 iter(o[,sentinel])函数,我正在尝试遍历 lst(列表) 并打印所有值,直到 'kdawg'

代码:

lst = [2,3,4,'kdawg',5,6,'hey'] 
 
class foo: 
    def __str__(self): 
        return str(lst) 
 
for i in iter(foo,'kdawg'): 
    print i 

我希望它返回:

2 
3 
4 

但是它连续地返回整个列表:

[2,3,4,'kdawg',5,6,'hey'] 

为什么我的 iter() 函数不起作用?