Python字符串转换成浮点数函数分享

yipeiwu_com6年前Python基础

利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456

from functools import reduce
 
def str2float(s):
  return reduce(lambda x,y:x+int2dec(y),map(str2int,s.split('.')))
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 str2int(s):
  return reduce(lambda x,y:x*10+y,map(char2num,s))
def intLen(i):
  return len('%d'%i)
def int2dec(i):
  return i/(10**intLen(i))
   
print(str2float('123.456'))

以上就是本代码的全部内容了,希望对大家学习Python能够有所帮助。

相关文章

Tensorflow实现卷积神经网络的详细代码

本文实例为大家分享了Tensorflow实现卷积神经网络的具体代码,供大家参考,具体内容如下 1.概述 定义: 卷积神经网络(Convolutional Neural Network,...

在Pycharm中执行scrapy命令的方法

在Pycharm中执行scrapy命令的方法

当你检查scrapy二进制文件时,你会注意到这么一段python script #!/usr/bin/python from scrapy.cmdline import execu...

实例讲解Python中函数的调用与定义

调用函数: #!/usr/bin/env python3 # -*- coding: utf-8 -*- # 函数调用 >>> abs(100) 100...

Django实现支付宝付款和微信支付的示例代码

Django实现支付宝付款和微信支付的示例代码

支付宝支付和微信支付是当今互联网产品常用的功能,我使用Django Rest Framework实现了网页上支付宝支付和微信支付的一个通用服务,提供rpc接口给其他服务,包括获取支付宝支...

python实现大战外星人小游戏实例代码

主程序 import pygame from pygame.sprite import Group from settings import Settings from game_...