You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中re.finditer返回对象有长度却无法迭代的问题

re.finditer迭代无输出的原因及解决方法

问题场景

以下代码运行正常,能正确匹配并迭代输出2个'TP':

import re

s = 'TP Tutorials Point TP'

out = re.findall(r'TP', s)

assert len(list(out)) == 2

# 此循环会打印2次匹配到的字符串
for m in out:
    print(m)

但使用re.finditer的代码却无法输出结果:

import re

s = 'TP Tutorials Point TP'

out = re.finditer(r'TP', s)

# 这一步断言通过
assert len(list(out)) == 2

# !!! 此处无任何输出 !!!
for m in out:
    print(m)

原因分析

核心区别在于两个方法的返回类型特性:

  • re.findall返回列表,列表是可重复遍历的容器,无论调用多少次list()或循环遍历,内部元素都会保留。
  • re.finditer返回一次性迭代器,迭代器只能被遍历一次——当你执行list(out)时,已经把迭代器内的所有匹配结果全部取出转成了列表,此时迭代器已被"耗尽",后续再对它遍历自然没有元素输出。

解决方法

只需先把迭代器的结果转成列表保存,再用这个列表完成断言和遍历操作:

import re

s = 'TP Tutorials Point TP'

out = re.finditer(r'TP', s)
# 将迭代器转成列表保存
matches = list(out)

assert len(matches) == 2

# 遍历保存后的列表,正常输出匹配结果
for m in matches:
    print(m)

也可以调整操作顺序,先遍历迭代器收集结果,再做断言:

import re

s = 'TP Tutorials Point TP'

out = re.finditer(r'TP', s)
matches = []
for m in out:
    print(m)
    matches.append(m)

assert len(matches) == 2

内容的提问来源于stack exchange,提问作者Wakan Tanka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:39:06