跳过列表压缩的2行

2024-04-25 15:01:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图利用列表理解对一个非常大的文件中的数据进行排序。文件结构如下:

THING
info1
info2
info3
THING
info1
info2
info3

。。。等等。你知道吗

基本上是试图将所有info1收集到一个列表中,将所有info2收集到另一个列表中。我有一个以前的脚本做这个,但它的速度很慢。我还试图使它面向对象,这样我可以更有效地使用数据。你知道吗

旧脚本:

info1_data = []
info2_data = []
with open(myfile) as f:
    for line in f:
        if re.search('THING',line):
            line=next(f)
            info1_data.append(line)
            line=next(f)
            info2_data.append(line)

新脚本:

def __init__(self, file):
    self.file = file

def sort_info1(self):
    with self.file as f:
        info1_data = [next(f) for line in f if re.search('THING',line)]
    return info1_data

def sort_info2(self):
    with self.file as f:
        info2_data = [next(f).next(f) for line in f if re.search('THING',line)]
    return info2_data

新脚本用于以列表的形式获取info1\u数据。但是,要获取info2\数据,我找不到任何使用此方法跳过两行的方法。我猜在next(f).next(f)。它运行,但不产生任何东西。你知道吗

这可能吗?你知道吗

非常感谢。你知道吗

在摩西的帮助下,我得到了这个解决方案。岛是非常混乱的,虽然我不完全理解它,即使在阅读了python.docs文件. iterable是否获取数据(即info1或info2),或者start、stop和step是否指示提取哪些数据?你知道吗

islice(iterable,start,stop[,step])

from itertools import islice
import re

class SomeClass(object):
    def __init__(self, file):
        self.file = file

    def search(self, word, i):
        self.file.seek(0) # seek to start of file
        for line in self.file:
            if re.search(word, line) and i == 0:
                line = next(self.file)
                yield line
            elif re.search(word, line) and i == 1:
                line = next(self.file)
                line = next(self.file)
                yield line

    def sort_info1(self):
        return list(islice(self.search('THING',0), 0, None, 2))

    def sort_info2(self):
        return list(islice(self.search('THING',1), 2, None, 2))


info1 = SomeClass(open("test.dat")).sort_info1()
info2 = SomeClass(open("test.dat")).sort_info2()

Tags: 数据selfre脚本列表searchdatadef
2条回答

你可以这样做:

def sort_info2(self):
    with self.file as f:
        info2_data = [(next(f),next(f))[1] for line in f if re.search('THING',line)]
    return info2_data

但看起来有点奇怪!你知道吗

您应该将seek文件返回到开头,以便从文件的开头重复搜索。此外,还可以使用生成器函数将搜索操作与数据生成分离。然后使用^{}跨行:

from itertools import islice

class SomeClass(object):
    def __init__(self, file):
        self.file = file

    def search(self, word):
        self.file.seek(0) # seek to start of file
        for line in self.file:
            if re.search(word, line):
                # yield next two lines
                yield next(self.file)
                yield next(self.file)

    def sort_info1(self):
        return list(islice(self.search('THING'), 0, None, 2))

    def sort_info2(self):
        return list(islice(self.search('THING'), 1, None, 2))

但是,我建议您不要传递文件,而是传递文件的路径,以便每次使用后都可以关闭文件,以避免在不需要(或尚未需要)资源时占用资源。你知道吗

相关问题 更多 >