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]
谢谢!
>>> 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)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |