輸入示例:如何在文件解壓縮嵌套循環:Python的
Blank {Line0}
Loop 3 {Line1}
Blank {Line1a}
Label2: Blank {Line2}
Blank {Line3}
Loop 2 {Line4}
Blank {Line4a}
Label1: Blank {Line5} # I need to repeat the Jump statements as many times as mentioned in the Loop before the Label statement. Always The Loop statements precedes the immediate Jump statement. So here Line5, Lin6 and Line7 gets repeated twice. Jump to label1 so print line5, Line6 (since it has nothign going on) and Line7 is the end of Jump statement. Repeat it twice. Since Loop 2 {Line4} says do the following Jump Twice.
Blank {Line6}
Jump Label1 {Line7}
Blank {Line8}
Jump Label2 {Line9} # This jumps back to Label2. Which repeats everything until this line including the expanded inner loop ... This is the nested loop.
Blank {Line10}
輸出例:
Line0
Line1
Line1a
Line2
Line3
Line4
Line4a
Line5
Line6
Line7
Line5
Line6
Line7
Line8
Line9
Line2
Line3
Line4
Line4a
Line5
Line6
Line7
Line5
Line6
Line7
Line8
Line9
Line2
Line3
Line4
Line4a
Line5
Line6
Line7
Line5
Line6
Line7
Line8
Line9
Line10
我現在有,對於在文件中循環和重複循環工作的代碼。但打破上面給出的輸入文件。我嘗試從這裏實現@Samy Arous方法:Using Python to Parse a File for Nested Loops但無法實現它。爲了清晰起見,將其作爲一個單獨的問題提出。
所有的行只是字符串...這是一個有點複雜的格式,所以只是給了一個簡單的。我們可以假設Blank,JUMP,LOOP都指導着需要完成的事情。無論是剛剛打印出來或重複基於循環和跳轉
我的代碼:
import sys
inputtfile = sys.stdin
inputfileContents = open(r'path to input file')
def extract(line):
return line[line.find('{') + 1: line.rfind('}')]
loopCount = 0
loopLines = []
inLoop = False
for line in inputfileContents:
if line.startswith('Loop '):
loopCount = int(line.split()[1])
inLoop = True
elif line.startswith('Jump '):
loopLines.append(extract(line))
for i in range(loopCount):
for loopLine in loopLines:
print loopLine
#reset state variables to track next possible loop
loopCount = 0
inLoop = False
loopLines = []
elif inLoop:
loopLines.append(extract(line))
else:
print extract(line)
這段代碼甚至執行了嗎?這些行: 'inLoop = True' 'loopLines.append(extract(line))'它們在'if'語句和'elif'之間,這是無效的 – smac89 2014-10-16 22:10:32
@ smac89。我糾正了它。應該在elif內...縮進錯誤.. – Doodle 2014-10-16 22:17:13
歡迎使用stackoverflow。如果您更多地瞭解您的問題而不是更多地瞭解您的解決方案,您將在這裏獲得更好的答案如果我不清楚你想要解決什麼問題,我可能不會試着回答。一些提示,以改善您的問題:什麼是所需的輸出/行爲? '{LineX}'事情真的是你的輸入文件的一部分? – 2014-10-16 22:48:00