gpt4 book ai didi

python - 从 Python 文件中读取行的更好方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-03 13:51:30 28 4
gpt4 key购买 nike

这是我的 python 文件:-

TestCases-2
Input-5
Output-1,1,2,3,5
Input-7
Ouput-1,1,2,3,5,8,13

我想要的是这个:-

  • 变量test_no = 2(测试用例数量)
  • 列表testCaseInput = [5,7]
  • 列表testCaseOutput = [[1,1,2,3,5],[1,1,2,3,5,8,13]]

我试过这样做:

               testInput = testCase.readline(-10)

for i in range(0,int(testInput)):
testCaseInput = testCase.readline(-6)
testCaseOutput = testCase.readline(-7)

下一步就是在(',')的基础上把数字去掉,然后放到一个列表中。

奇怪的是,readline(-6) 没有给出预期的结果。

有没有更好的方法来做到这一点,显然我错过了。

我不介意在这里使用序列化,但我想让人们非常简单地编写一个文本文件,如我所展示的那样,然后从中取出数据。如何做到这一点?

最佳答案

readline 方法的负参数指定要读取的字节数。我不认为这是你想要做的。

相反,使用 readlines() 将所有内容一次拉入列表会更简单:

with open('data.txt') as f:
full_lines = f.readlines()

# parse full lines to get the text to right of "-"
lines = [line.partition('-')[2].rstrip() for line in full_lines]

numcases = int(lines[0])
for i in range(1, len(lines), 2):
caseinput = lines[i]
caseoutput = lines[i+1]
...

这里的想法是分离关注点(数据源、“-”的解析以及如何处理案例的业务逻辑)。这比每一步都有一个 readline() 和冗余的解析逻辑要好。

关于python - 从 Python 文件中读取行的更好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7874643/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com