【问题标题】:How do I convert a list of strings to a new list where each element is its core type? [duplicate]如何将字符串列表转换为每个元素都是其核心类型的新列表? [复制]
【发布时间】:2023-04-11 04:40:01
【问题描述】:

例如,

我有一个清单

list = ['1', 'hello', '524', '65.23']

如何将其转换为:

list_new = [1, 'hello', 524, 65.23]

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

这里不是 [string, string, string, string] 现在是 [int, string, int, float]

谢谢!

【问题讨论】:

    标签: python list types type-conversion


    【解决方案1】:
    >>> 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]
    

    【讨论】:

    • 贾米拉克!!!你去哪儿了!!!!! (你也打败了我+1)
    • 要处理带有空格的字符串或以数字字符开头的字符串,您还应该捕获SyntaxError
    • 好的改成普通的except来处理所有事情
    • 谢谢!对我有很大帮助!
    猜你喜欢
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    相关资源
    最近更新 更多