字符转浮点,看了评论写出来的。
Topic source感谢楼主!!!我想把它们先转成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'))
回楼上,其实你那个也是一回事。你用的是123+0.456,我用的是123456/1000,不过这里很有意思的是[123,456]这个list里,x + y并不是求和,而是拼接成123456。
- 1
莉莉娅的小暖炉
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()函数和乘方'**'的用法,了解了这个的话,做起来就轻松多了,惭愧惭愧。