将String转换回List

Jos*_*osh 2 python csv string

我昨天搞砸了并将数据框保存到了csv,在那个数据框中我有一个列是一个字符串列表.现在,当我从csv将其导入python时,字符串列表是一个字符串(字符串列表).有没有办法在导入时将其更改回字符串列表?

例:

testList = localGov["DataElements"][4]

testList
Out[62]: "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']"
Run Code Online (Sandbox Code Playgroud)

我能够得到的最接近的是使用以下内容,但它在一些角色前面留下了一个空格.

testList.strip("[]").replace("'","").split(",")
Out[74]: ['Ethnicity', ' Sex', ' Cause of Death', ' Count', ' Percent']
Run Code Online (Sandbox Code Playgroud)

Kas*_*mvd 9

ast.literal_eval是为了:

>>> from ast import literal_eval
>>> 
>>> literal_eval( "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']")
['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']
Run Code Online (Sandbox Code Playgroud)

  • @VigneshKalai然后你显然认为这是一个很好的答案.但没有upvote? (4认同)