将python字符串列表转换为它们的类型 [英] converting python list of strings to their type
本文介绍了将python字符串列表转换为它们的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出了python字符串列表,如何自动将其转换为正确的类型?意思是,如果我有:
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"]
我希望将其转换为列表
["hello", 3, 3.64, -1]
其中第一个元素是stuntng,第二个元素是int,第三个元素是float,第四个元素是int.
where the first element is a stirng, the second an int, the third a float and the fourth an int.
我该怎么做?谢谢.
推荐答案
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]
这篇关于将python字符串列表转换为它们的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文