免责声明:我对python很新!
如果我想要一个文件的所有行直到(编辑并包含)包含某些字符串的行stopterm
,是否有一种方法可以使用它的列表语法?我希望有类似的东西:
usefullines = [line for line in file until stopterm in line]
现在,我有
usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break
它不是世界末日,但由于Python语法的其余部分非常简单,我希望有一个思想 - > 1 Python线映射.
from itertools import takewhile usefullines = takewhile(lambda x: not re.search(stopterm, x), lines) from itertools import takewhile usefullines = takewhile(lambda x: stopterm not in x, lines)
这是一种保持stopterm线的方法:
def useful_lines(lines, stopterm): for line in lines: if stopterm in line: yield line break yield line usefullines = useful_lines(lines, stopterm) # or... for line in useful_lines(lines, stopterm): # ... do stuff pass
"我希望有一个思想 - > 1 Python线映射." 难道我们都不会喜欢以某种方式反映我们自然语言的编程语言吗?
你可以做到这一点,你只需要定义一次你独特的想法.然后你有你希望的1:1映射.
def usefulLines( aFile ): for line in aFile: yield line if line == stopterm: break
几乎就是这样.
for line in usefulLines( aFile ): # process a line, knowing it occurs BEFORE stopterm.
有更一般的方法.这个简单设计模式的lassevk
答案enum_while
和enum_until
概括.