Converting a List Representative String to an Actual List Object

I have a line 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 this character string into an actual list. I guess one could re-set numbers and quote later ( append()), but is there an easier way? Not sure how I would set this as a regular expression.

+3
source share
5 answers

Use ast.literal_eval .

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

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]")
+4
source

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]"

:

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

Try the following:

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 hacked, but it will work!

+1
source

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
source

Source: https://habr.com/ru/post/1796701/


All Articles