python迭代器的使用

#使用迭代器实现有限历史纪录搜索
from collections import deque

#迭代器,使用deque实现有限历史记录
def search( strings, target, historyNum):
record = deque( maxlen = historyNum)
for ss in strings:
if target in ss:
yield ss,record
record.append(ss)
#测试搜索
s = ( 'gps', 'beidou', 'galileo', 'beidou', 'glonass', 'gagan', 'qzss', 'beidou') #待搜索字符串
totalFind = 0
for t,record in search(s, 'ido', 2): #搜索包含ido的字符串,搜索过程中保存2条历史记录
for ss in record:
print(ss) #输出历史记录
print(t) #输出搜索到的字符串
print( '-'* 5) #用于分隔迭代器的输出
totalFind = totalFind + 1
print( '总共找到 %d 次目标字符' % totalFind)


猜你喜欢

转载自blog.csdn.net/zxjohnson/article/details/79357691