Discuss / Python / 第三题,你们都用split的嘛

第三题,你们都用split的嘛

Topic source

花朝zhe

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

def str2float(s): num1="" num2="" count=0 for i in s: if i !=".": num1+=i count+=1 else: count+=1 break num2=s[count:] num=num1+num2 count=len(s)-count def fun(x,y): return 10x+y def char2int(n): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[n] return reduce(fun,map(char2int,num))/(10**count)

print(str2float("3.1415926"))

from functools import reduce def str2float(s): count=0 for x in s: if x!='.': count=count+1 else: count=count+1 break count1=len(s)-count def char2num(s): return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s] def f(x,y): return(10x+y) return reduce(f,map(char2num,s))/(10*count1)

这样写为什么不对,报错是KEYERROR,但是教程里面不也是直接把函数直接作用于s的吗?

肉厚汤圆

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

上面的写法不对是因为: {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}是一个字典, 通过下标[s]来找到对应的字符 就类似name是一个字典,daniel是key,name['daniel']就是找到daniel的value 但是这个字符串里有 . 这个符号,但是你的字典里却没有 所以会报KEYERROR


  • 1

Reply