Convert a list of strings to either int or float

后端 未结 6 684
感情败类
感情败类 2020-12-21 00:14

I have a list which looks something like this:

[\'1\', \'2\', \'3.4\', \'5.6\', \'7.8\']

How do I change the first two to int

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 00:39

    Why not use ast.literal_eval?

    import ast
    
    [ast.literal_eval(el) for el in lst]
    

    Should handle all corner cases. It's a little heavyweight for this use case, but if you expect to handle any Number-like string in the list, this'll do it.

提交回复
热议问题