Python:项目项目直到项目中的stopterm?

Phi*_*l H 3 python

免责声明:我对python很新!

如果我想要一个文件的所有行直到(编辑并包含)包含某些字符串的行stopterm,是否有一种方法可以使用它的列表语法?我希望有类似的东西:

usefullines = [line for line in file until stopterm in line]
Run Code Online (Sandbox Code Playgroud)

现在,我有

usefullines = []
for line in file:
    usefullines.append(line)
    if stopterm in line:
        break
Run Code Online (Sandbox Code Playgroud)

它不是世界末日,但由于Python语法的其余部分非常简单,我希望有一个思想 - > 1 Python线映射.

Ste*_*wig 10

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)
Run Code Online (Sandbox Code Playgroud)

这是一种保持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
Run Code Online (Sandbox Code Playgroud)


S.L*_*ott 5

"我希望有一个思想 - > 1 Python线映射." 难道我们都不会喜欢以某种方式反映我们自然语言的编程语言吗?

你可以做到这一点,你只需要定义一次你独特的想法.然后你有你希望的1:1映射.

def usefulLines( aFile ):
    for line in aFile:
        yield line
        if line == stopterm:
            break
Run Code Online (Sandbox Code Playgroud)

几乎就是这样.

for line in usefulLines( aFile ):
    # process a line, knowing it occurs BEFORE stopterm.
Run Code Online (Sandbox Code Playgroud)

有更一般的方法.这个简单设计模式的lassevk答案enum_whileenum_until概括.