[三个版本]自定义int()函数(Python实现)

来源:互联网 发布:返利网淘宝卖家知道吗 编辑:程序博客网 时间:2024/06/04 19:15

代码一:

from functools import reducedef int(string):    def f(x, y):        return x*10 + y    def m(c):        return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8,'9': 9}[c]    return reduce(f, map(m, string))


代码二:

from functools import reducedef int(string):    def f(x, y):        return x*10 + y    return reduce(f, map(lambda x: ord(x) - ord('0'), string))

代码三:

from functools import reducedef int(string):    return reduce(lambda x, y: x*10 + y, map(lambda x: ord(x) - ord('0'), string))



原创粉丝点击