Discuss / Python / 想请教为什么break和continue都可以

想请教为什么break和continue都可以

Topic source

知一_

#1 Created at ... [Delete] [Delete and Lock User]

-- coding: utf-8 --

from functools import reduce def str2float(s): def fn(x,y): return x10+y def char2num(r): return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[r] for i in range(0,len(s)): if s[i]=='.': a=i continue s0=[n for n in s if n!='.'] t=reduce(fn,list(map(char2num,s0))) return t/(10*(len(s)-(a+1))) print('str2float 123.456',str2float('123.456'))

在if语句哪里试了break和continue结果都没问题,但总觉得如果用break就不会往后循环了,很疑惑,求解~~

知一_

#2 Created at ... [Delete] [Delete and Lock User]

好像不加上break和continue也可以。。。脑袋混乱,用法极为不清楚,求指点

NeptuneAR

#3 Created at ... [Delete] [Delete and Lock User]
在此插入代码

from functools import reduce def str2float(s): def fn(x,y): return x10+y def char2num(r): return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9}[r] for i in range(0,len(s)): if s[i]=='.': a=i continue s0=[n for n in s if n!='.'] t=reduce(fn,map(char2num,s0)) return t/(10*(len(s)-(a+1))) print('str2float(\'123.456789\') =', str2float('123.456789')) 这是你的代码,最后return的是才是10的几次方,这里因为你只是要找到‘.’的位置所以用不用break/continue都行,但最好用break直接跳出循环减少循环次数,但实际上用a=s.index('.')就可以了


  • 1

Reply