使用 Python 为嵌套循环解析文件 [英] Using Python to Parse a File for Nested Loops
问题描述
当前 Python 读取文件的每一行并执行函数 doStep()
.这个函数被传递给正在读取的行上的任何内容.
Currently Python reads each line of a file and executes a function doStep()
. This function is passed whatever is on the line being read.
data.txt
a
b
c
b
read.py
fin = open('data.txt')
for step in fin:
doStep(step)
Python 将执行
doStep(a)
doStep(b)
doStep(c)
doStep(b)
问题:如果我想在data.txt中定义嵌套循环,应该如何定义和解析?嵌套和循环迭代次数应在data.txt
Question: If I want to define nested loops in data.txt, how should it be defined and parsed? The nesting and number of loop iterations should be defined in data.txt
例如,通过阅读data.txt我想循环这个5次
For example, by reading data.txt I want to loop this 5 times
doStep('a')
doStep('b')
doStep('c')
循环 10 次
doStep('x')
doStep('y')
doStep('z')
并重复所有内容 3 次(嵌套).
and repeat everything 3 times (nesting).
推荐答案
您可以使用普通的 data.py 文件代替 data.txt 文件.在那里,您可以从 read.py 导入例程,并使用所有 Python 魔法执行功能/方法.
Instead of an data.txt file you could use a normal data.py file. There you could import the routines from your read.py and executes the funktions/methodes with all the python magic.
这篇关于使用 Python 为嵌套循环解析文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!