读取文件然后停止然后继续直到给定行

Read file then stop then continue until given line

Python3.7题.

我有一个看起来像这样的文件: 1 10 10 10 3 25 29 10 52 55 30 70 70 20 0

其中 1 表示将有 1 行,3 表示将有 3 行,0 表示文件结束。如何实现?

我试过了

def read_each_course(filename):
    with open(filename, 'r') as f:
        lines = []
        content = f.readlines()
        lines += [x.rstrip() for x in content]
    for i in lines:
        while True:
            if str(i).count(" ") == 0:
                lines_to_read = int(i)
                break
        return lines_to_read, next(i)

但这行不通我明白了

TypeError: 'str' object is not an iterator
 for the next(i).

我的想法是获取一个列表列表,如下所示: [[1, [10, 10, 10]], [3, [25, 29, 10], [52, 55, 30], [70, 70, 20]]]

但是,我不确定这种设计总体上是否是个好主意?或者它应该是一个单一的链接列表,因为最终目标是因为 3 个数字是坐标,我将不得不只使用下一个项目,例如 x2-x1,y2-y1,如果遗漏(额外成本)其中总成本是炒作。我可以计算出 xy 三角形的大小。

这段代码应该可以解决问题,对于你的设计问题,我不知道它在我看来是基于意见的。所以我会专注于代码。

在你的代码行中是一个列表,我是这个列表的一个元素。您在列表元素之一上调用下一个,而不是在此处的列表中。我不得不承认我不明白你的代码的逻辑。所以我真的帮不上忙。

def read_each_course(filename):

    result = []
    current = []
    with open(filename) as f_in:

        for line in f_in:  # loop  over the file line by line

            spt = line.strip().split()  # split
            if len(spt) == 1: # one elem

                if current: # not the first one
                    result.append(current)
                    current = []

                if spt[0] == 0: # end of file
                    break

                current.append(int(spt[0]))

            else:
                current.append(list(map(int, spt)))

    return result

RomainL 对答案的修改简化了逻辑。

它使用迭代器来解析文件。

def read_each_course(filename):

    result = []
    with open(filename) as f:
        it = iter(f)
        while True:
            count = int(next(it))

            if count == 0:         # Found the stop marker
                break

            current = [count]
            for _ in range(count):
                current.append([int(v) for v in next(it).strip().split()])
            result.append(current)
    return result


print(read_each_course("file2.txt"))

按要求输出。