python中高阶函数的练习(将一个字符串转换成整型)
题目要求:
将一个字符串转换成整型
‘12345’—12345
‘0’:0
‘1’:1
‘2’:2
…
‘9’:9
from functools import reduce
def str2int(s):
def char2int(ch):
c = {str(x): x for x in range(10)}
print(c)
return c[ch]
def fun(n1, n2):
return n1 * 10 + n2
# [2,4,3,1,2,4,1,2]
return reduce(fun, map(char2int, s))
num = str2int('24312412')
print(type(num), num)
输出结果:
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
<class 'int'> 24312412