最新公告
  • 欢迎您光临站盟网(原知事网),一个优质的网站源码基地、精品网站模板和插件。欢迎加入永久SVIP
  • python中str转int的方法

    正文概述 知事网   2020-12-20 11:12   397

    在python中使用过程中,我们常常会遇到数据类型转换的问题。本文小编整理了python中str转int的两种方法:map函数法和lambda表达式法。具体内容请看本文。

    方法一:map函数法

    map() 会根据提供的函数对指定序列做映射。

    def square(x):
        return x ** 2
    a = [1,2,3,4,5,6]
    b = map(square,a)
    b = list(b)
    print(b)
    #result:[1, 4, 9, 16, 25, 36]
     
    print(list(map(lambda x,y:x + y ,[1,2,3,4,5],[10,20,30,40,50])))
    
    #result:[11, 22, 33, 44, 55]

    方法二:lambda表达式法

    from functools import reduce
    DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
    def str2int(str):
        def char2num(s):
            return DIGITS[s]
        return reduce(lambda x,y:x*10+y,map(char2num,str))
    str = '5632'
    nums = str2int(str)
    print('str-->int:',nums)

    以上就是小编总结的python中str转int的两种方法,大家可以选择自己喜欢的方式进行转换哟~

    转载自:python学习网 https://www.py.cn/


    站盟网 » python中str转int的方法

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者
    请选择支付方式
    ×
    支付宝支付
    微信支付
    余额支付
    ×
    微信扫码支付 0 元