首页 > 编程语言 > 详细

Python之str型转成int型

时间:2017-07-18 16:30:26      阅读:398      评论:0      收藏:0      [点我收藏+]

str转int:

1 def fn(x,y):
2     return x*10+y
3 
4 def char2num(s):
5     return {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}[s]  # 特别注意这里,后面还有个 [s]
6 
7 print(type(reduce(fn, map(char2num, 1738785))))
8 print(reduce(fn, map(char2num, 1738785)))

输出如下:

1 <type int>
2 1738785

整理成一个 str2int 函数就是如下喽:

 1 from functools import reduce
 2 
 3 def str2int(s):
 4     def fn(x,y):
 5         return x*10+y
 6     def char2num(s):
 7         return {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}[s]
 8     return reduce(fn,map(char2num,s))
 9 
10 print(str2int(365779))
11 print(type(str2int(365779)))

 

用匿名函数lambda再简化一下就成了下面这个样子:

1 def str2int(s):
2     return reduce(lambda x,y:x*10+y, map(lambda s:{0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}[s], s))

WOC,就一行代码哦,够简单!

 

Python之str型转成int型

原文:http://www.cnblogs.com/fallenmoon/p/7200947.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!