开发者

Converting a string that represents a list, into an actual list object [duplicate]

开发者 https://www.devze.com 2023-02-14 23:54 出处:网络
This question already has answers here: How to convert string representation of list to a list (19 answers)
This question already has answers here: How to convert string representation of list to a list (19 answers) Closed 4 months ago.

I have a string that represents a list:

"[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"

I would like to turn that litteral string into an actual list. I suppose to could regex out the numbers and loop over then (append()) but is there an easier way? Not sure how I would开发者_如何学JAVA set that up as a regex.


Use ast.literal_eval.

>>> import ast
>>> i = ast.literal_eval('[22, 33, 36, 41, 46, 49, 56]')
>>> i[3]
41


Yet another way:

import json
x=json.loads("[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]")


If your actual string is

s = "[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"

then this will do the trick:

[int(n) for n in s[1:-1].split(', ')]


Try this:

sl = "[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]"
sl = sl.lstrip('[')
sl = sl.rstrip(']')
sl = sl.split(',')

Ugly and hacky, but it'll work!


You can use the built-in eval http://docs.python.org/library/functions.html#eval

>>> lst = eval("[22, 33, 36, 41, 46, 49, 56, 72, 85, 92, 95, 98, 107, 118, 120, 123, 124, 126, 127, 130, 149, 157, 161, 171, 174, 177, 187, 195, 225, 302, 316, 359, 360, 363, 396, 479, 486, 491]")
>>> type(lst)
<type 'list'>
>>> lst[0]
22
0

精彩评论

暂无评论...
验证码 换一张
取 消