简体   繁体   English

将列表字符串转换为int列表

[英]Convert string of list into list of int

how do I convert a string of integer list into a list of integers? 如何将整数列表的字符串转换为整数列表?

Example input: (type: string) 输入示例:(类型:字符串)

"[156, 100, 713]"

Example conversion: (type: list of int) 转换示例:(类型:int列表)

[156, 100, 713]

Try this: 尝试这个:

import ast
res = ast.literal_eval('[156, 100, 713]')

Read more about ast.literal_eval in python docs. 在python文档中阅读有关ast.literal_eval的更多信息。

use ast.literal_eval on it and you're done. 在上面使用ast.literal_eval完成。 Here you don't have all the security issues of regular eval and you don't need to worry about making sure your string is well formed, etc. Of course, if you really want to parse this thing yourself, you can do it with a pretty simple list-comprehension: 在这里,您没有常规eval所有安全性问题,也不必担心确保字符串格式正确等。当然,如果您真的想自己解析此事情,则可以使用一个非常简单的列表理解:

s = "[156, 100, 713]"
print [ int(x) for x in s.translate(None,'[]').split(',') ]
>>> import json
>>> a = "[156, 100, 713]"
>>> json.loads(a)
[156, 100, 713]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM