Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

python - Converting a string that represents a list, into an actual list object

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 set that up as a regex.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use ast.literal_eval.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...