How to cast string back into a list

拜拜、爱过 提交于 2019-12-19 07:47:46

问题


I have a list:

ab = [1, 2, a, b, c]

I did:

strab = str(ab).

So strab is now a string.

I want to cast that string back into a list.

How can I do that?


回答1:


The easiest and safest way would be to use ast.literal_eval():

import ast

ab = [1, 2, 'a', 'b', 'c']    # a list
strab = str(ab)               # the string representation of a list
strab
=> "[1, 2, 'a', 'b', 'c']"

lst = ast.literal_eval(strab) # convert string representation back to list
lst
=> [1, 2, 'a', 'b', 'c']

ab == lst                     # sanity check: are they equal?
=> True                       # of course they are!

Notice that calling eval() also works, but it's not safe and you should not use it:

eval(strab)
=> [1, 2, 'a', 'b', 'c']



回答2:


Use the ast package:

import ast
lst = ast.literal_eval(strab)



回答3:


In the context of setting a numpy array element with a sequence, you can use the built-in join to bypass setting it to a string:

str_list_obj = '-'.join(list_obj)

and afterwards when needed split the string sequence again with the same connector (provided it does not appear in the list's strings):

og_list_obj = str_list_obj.split("-")



来源:https://stackoverflow.com/questions/17768509/how-to-cast-string-back-into-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!