如何在迭代器中有2个哨兵?

时间:2019-07-29 06:07:06

标签: python iterator

我正在使用以下代码段读取文件的所有内容,该内容在以start_string和stop_string分隔的两行之间

with open(file_name) as file:
    start_token = next(l for l in file if l.strip()==start_string) # Used to read until the start token
    result = [line for line in iter(lambda x=file: next(x).strip(), stop_string) if line]

return `result`

我的问题是我发现stop_string有时可以具有2个不同的值,所以我想将它们指定给哨兵。

类似

result = [line for line in iter(lambda x=file: next(x).strip(), stop_string or stop_string_2") if line]

想法是前哨是stop_strin g或s top_string_2

上面的代码显然是错误的,但是我该怎么做呢?

如何在一次迭代中有多个哨兵?

1 个答案:

答案 0 :(得分:0)

我认为这不是一个特别好的方法。我可以建议一种替代方法:

stop_strings = {stop_string, stop_string2}
with open(file_name) as file:
    iterator = file.iter()
    for line in iterator:
        if line.strip() == start_string:
            break

    result = []
    for line in iterator:
        result.append(line)
        if line.strip() in stop_strings:
            break

如果您坚持使用功能样式,则可以:

import itertools as it

stop_strings = {stop_string, stop_string2}
with open(file_name) as file:
    after_start = it.islice(it.dropwhile(lambda s: s.strip() != start_string),
                            1, None)
    before_end = it.takewhile(lambda s: s.strip() not in stop_strings, after_start)
    result = list(before_end)