如何将字符串列表转换为新列表,其中每个元素是其核心类型?

lor*_*rde 2 python types list type-conversion

例如,

我有一份清单

list = ['1', 'hello', '524', '65.23']
Run Code Online (Sandbox Code Playgroud)

如何将其转换为:

list_new = [1, 'hello', 524, 65.23]
Run Code Online (Sandbox Code Playgroud)

其中每个元素不再是字符串,而是实际类型.

而不是[string,string,string,string]它现在是[int,string,int,float]

谢谢!

jam*_*lak 7

>>> import ast
>>> items = ['1', 'hello', '524', '65.23']
>>> def convert(x):
        try:
            return ast.literal_eval(x)
        except:
            return x


>>> [convert(x) for x in items]
[1, 'hello', 524, 65.23]
Run Code Online (Sandbox Code Playgroud)