Discuss / Python / 字符转浮点,看了评论写出来的。

字符转浮点,看了评论写出来的。

Topic source

def chr2int(s): return s

def int2float(x,y): return int(x+y) / 10**len(y)

s = '123.456' L = list(map(chr2int,s.split('.'))) r = reduce(int2float,L) print(r)

一行版: print(reduce(lambda x,y:int(x+y)/10**len(y),map(lambda s:s,'123.456'.split('.'))))

主要是不知道split()函数和乘方'**'的用法,了解了这个的话,做起来就轻松多了,惭愧惭愧。

撩我心丶

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

int(x+y) 会让它先加在除吗

水慕流影

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

感谢楼主!!!我想把它们先转成int,然后就没有然后了 from functools import reduce def str2float(s): DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} def str2int(s): def fn(x, y): return x 10 + y def char2num(s): return DIGITS[s] return reduce(fn, map(char2num, s)) def int2float(x,y): return str2int(x+y) / 10*len(y) L = s.split('.') r = reduce(int2float,L) return r print(str2float('123.456'))

不是应该先int(y)/10**len(y) +int (x)?

回楼上,其实你那个也是一回事。你用的是123+0.456,我用的是123456/1000,不过这里很有意思的是[123,456]这个list里,x + y并不是求和,而是拼接成123456。

哎呀,犯傻了,s.split()分割后的list里元素还是字符,我居然理解成直接分割成了整数。 理解错误了,应该是['123','456']。


  • 1

Reply