How to convert list of intable strings to int

前端 未结 6 1361
我在风中等你
我在风中等你 2020-12-06 13:28

In Python, I want to convert a list of strings:

l = [\'sam\',\'1\',\'dad\',\'21\']

and convert the integers to integer types like this:

6条回答
  •  执笔经年
    2020-12-06 13:43

    For multidimenson lists, use recursive technique may help.

    from collections import Iterable
    def intify(maybeLst):
        try:
            return int(maybeLst)
        except:
            if isinstance(maybeLst, Iterable) and not isinstance(lst, str):
                return [intify(i) for i in maybeLst] # here we call intify itself!
            else:
                return maybeLst
    
    maybeLst = [[['sam', 2],'1'],['dad','21']]
    print intify(maybeLst) 
    

提交回复
热议问题