我遇到了正在处理的问题。
它涉及打开一个读取一行的文件,然后将文件中的下两行与之比较。 然后向下移动一行,即文件中的第二行,然后再将下两行比较。
我很难创建一个循环来完成这些步骤。
到目前为止,我已经完成了这个
write_file = input_file[:-3] + "bak"
read_file = input_file
with open(write_file, "w") as write:
with open(read_file,"r") as read:
for line in read:
line1 = line
谢谢。
答案 0 :(得分:1)
类似的东西:
tri_lines = [lines[i:i+3] for i in range(0,len(lines),3)]
#Then you can iterate through:
For triplet in tri_lines:
# your code here, compare tri_lines[0] with tri_lines[1] etc.
我将让您完成将文件的所有行放入列表的任务。
请注意,您需要进行一些简单的验证来处理文件中没有可被3整除的行数的情况。
你甚至可以做到for triplet in [lines[i:i+3] for i in range(0,len(lines),3)]:
if triplet[0] == triplet[1]:
#do something
if triplet[0] == triplet[2]:
#do something
虽然这可能不那么清楚
答案 1 :(得分:1)
像@Matt Coubrough所说,这不是一个QnA论坛。在来到这里期待有人为你解决问题之前,你应该尝试自己解决问题。
为了让你走上正轨,这里有一些伪代码
//NOTE: This pseudocode assumes there are atleast 3 lines in the file
line1 = file.getLine()
line2 = file.getLine()
line3 = file.getLine()
//compare line1, line2, and line3
while(fileIsNotEmpty) {
line1 = line2
line2 = line3
line3 = file.getLine()
//compare line1, line2, and line3
}