开发者社区> 问答> 正文

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

Python 3.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三角形的个数。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-21 11:27:39 456 0
2 条回答
写回答
取消 提交回答
  • 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"))
    

    根据需要输出。

    回答来源:stackoverflow

    2020-03-21 11:40:41
    赞同 展开评论 打赏
  • ?

    2020-03-21 11:28:35
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载