标签:保留符合要求的n个条目 括号匹配
#保留符合要求的N个条目 from collections import deque def search(lines,pattern,history=5): previous_lines = deque(maxlen=history)#队列 for li in lines: if pattern in li: yield li,previous_lines#找到pattern,并yield previous_lines.append(li)#入队列 #Example use om s file if __name__ == ‘__main__‘: with open(r‘/etc/passwd‘)as f:#被查找文件 for line,prevlines in search(f,‘root‘,6): for pline in prevlines:#输出队列 print(pline,end=‘‘) print(‘-‘*20)
#括号匹配 stack = [] for c in exp: if c in (t[0] for t in brackets):#依次找到所有左括号,并入栈 stack.append(c) elif c in (t[1] for t in brackets):#判断右括号 if not len(stack): print(‘Error‘)#栈空,则不匹配 break left = stack.pop()#找到栈顶元素所匹配的右括号 bs = [t[1] for t in brackets if t[0] == left] if bs[0] != c:#判断栈顶右括号是否与当前右括号相匹配 print(‘Error‘) break else: if len(stack):#栈空,则匹配 print(‘Error‘) else: print(‘Ok‘)
本文出自 “11727697” 博客,请务必保留此出处http://11737697.blog.51cto.com/11727697/1829401
标签:保留符合要求的n个条目 括号匹配
原文地址:http://11737697.blog.51cto.com/11727697/1829401