converting python list of strings to their type

后端 未结 7 659
旧时难觅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:25

    import ast
    
    L = ["hello", "3", "3.64", "-1"]
    
    def tryeval(val):
      try:
        val = ast.literal_eval(val)
      except ValueError:
        pass
      return val
    
    print [tryeval(x) for x in L]
    

提交回复
热议问题