[英]Reiterate for loop reading a file until condition is met
我想逐行讀取文件。 這些行包含運算符和數字。 如果它是“+”我將添加后面的數字,它是“ - ”我將減去后面的數字。 這將保存在計數變量中。 然后,此計數變量將存儲在列表中。 我將繼續遍歷文件,直到找到重復的計數值。 我的想法是繼續循環,直到我找到重復(因此我的條件)。 但是當我到達文件的末尾時,我需要重新開始!! 因此,文件末尾的計數現在將從頭開始
while循環然后循環
def computeProblemOnePointFive(inputFileString):
inputFile = open(inputFileString, "r")
count = 0
countsList=[]
while len(countsList) == len(set(countsList)):
for line in inputFile:
if "+" in line:
value = int(line.strip("+"))
count = count + value
countsList.append(count)
if "-" in line:
value = int(line.strip("-"))
count = count - value
countsList.append(count)
return countsList[-1]
潛在的解決方案可能正在發展
inputFile = open(inputFileString, "r")
進入while循環
def computeProblemOnePointFive(inputFileString):
# the line was here previously
count = 0
countsList=[]
while len(countsList) == len(set(countsList)):
inputFile = open(inputFileString, "r") #the line that was moved
for line in inputFile:
if "+" in line:
value = int(line.strip("+"))
count = count + value
countsList.append(count)
if "-" in line:
value = int(line.strip("-"))
count = count - value
countsList.append(count)
return countsList[-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.