|
回复 11 # qibbxxt 的帖子
通过异常的话,大概是这样的:- # -*- coding: cp936 -*-
- class JumpException(Exception):
- """为转跳过程定义的异常"""
- def __init__(Self,tag):
- Exception.__init__(Self);
- Self.Tag = tag;
- def main():
- for i in range(1,10):
- try:
- for j in range(i,10):
- for k in range(j,10):
- for l in range(k,10):
- for m in range(l,10):
- try:
- for n in range(m,10):
- if n == 1:
- #在某些情况下只跳出一层
- raise JumpException('m');
- elif n == m:
- #在某些情况下跳出多层
- raise JumpException('i');
- except JumpException, e:
- if e.Tag == 'm':
- print 'm=',m
- else:
- raise e;
- except JumpException, e:
- if e.Tag == 'i':
- print 'i=', i;
- else:
- print e;
- if __name__ == '__main__':
- main();
复制代码
也可以通过中间变量来达到:
- def main():
- status = '0';
- for i in range(1,10):
- for j in range(i,10):
- for k in range(j,10):
- for l in range(k,10):
- for m in range(l,10):
- for n in range(m,10):
- if n == 1:
- #在某些情况下只跳出一层
- status = 'm';
- break;
- elif n == m:
- #在某些情况下跳出多层
- status = 'i';
- break;
- if status == 'm':
- print "m =",m;
- elif status == '0':
- continue;
- else:
- break;
- if status == 'l':
- print "l =",l;
- elif status == '0':
- continue;
- else:
- break;
- if status == 'k':
- print "k =",k;
- elif status == '0':
- continue;
- else:
- break;
- if status == 'j':
- print "j =",j;
- elif status == '0':
- continue;
- else:
- break;
- if status == 'i':
- print "i =",i;
- elif status == '0':
- continue;
- else:
- break;
复制代码
但是上面的代码有些冗余,因为实际上只需要在个别层之间跳转,可以将需要跳转的地方封装成函数:
- def A(i):
- for j in range(i,10):
- for k in range(j,10):
- for l in range(k,10):
- for m in range(l,10):
- re = B(m);
- if re == 'm':
- print 'm =',m;
- elif re == '0':
- continue;
- else:
- return re;
-
- return '0';
- def B(m):
- for n in range(m,10):
- if n == 1:
- #在某些情况下只跳出一层
- return 'm';
- elif n == m:
- #在某些情况下跳出多层
- return 'i';
-
- def main():
- status = '0';
- for i in range(1,10):
- if A(i) == 'i':
- print "i =",i;
- else:
- continue;
复制代码
输出的结果都一样:
m = 1
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
PS:使用直接跳转也行,但是MATLAB好像没有GOTO语句
|
|