converting python list of strings to their type

后端 未结 7 651
旧时难觅i
旧时难觅i 2020-12-05 19:57

given a list of python strings, how can I automatically convert them to their correct type? Meaning, if I have:

[\"hello\", \"3\", \"3.64\", \"-1\"]
<         


        
7条回答
  •  再見小時候
    2020-12-05 20:21

    I accomplished the same using json.loads method

    def f(l):
        for i in l:
            try:
                yield json.loads(i)
            except:
                yield i
    

    Test:

    In [40]: l
    Out[40]: ['hello', '3', '3.64', '-1']
    
    In [41]: list(f(l))
    Out[41]: ['hello', 3, 3.64, -1]
    

提交回复
热议问题