为什么takewhile()跳过第一行? [英] Why does takewhile() skip the first line?

查看:136
本文介绍了为什么takewhile()跳过第一行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的文件:

1
2
3
TAB
1
2
3
TAB

I想要读取TAB之间的行作为块。

I want to read the lines between TAB as blocks.

import itertools

def block_generator(file):
    with open(file) as lines:
        for line in lines:
            block = list(itertools.takewhile(lambda x: x.rstrip('\n') != '\t',
                                             lines))
            yield block

我想用它是这样的:

blocks = block_generator(myfile)
for block in blocks:
    do_something(block)

我得到的所有块都以第二行开头,如 [2, 3] [2,3] ,为什么?

The blocks i get all start with the second line like [2,3] [2,3], why?

推荐答案

这是使用groupby的另一种方法

Here is another approach using groupby

from itertools import groupby
def block_generator(filename):
    with open(filename) as lines:
        for pred,block in groupby(lines, "\t\n".__ne__):
            if pred:
                yield block

这篇关于为什么takewhile()跳过第一行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆