gpt4 book ai didi

python - 将字符串转换回列表

转载 作者:行者123 更新时间:2023-11-28 20:05:06 24 4
gpt4 key购买 nike

我昨天搞砸了,将一个 datframe 保存到 csv,在那个 dataframe 中我有一个列,它是一个字符串列表。现在,当我将字符串列表从 csv 导入回 python 时,它是一个字符串(字符串列表)。有没有一种方法可以在导入时将其改回字符串列表?

例子:

testList = localGov["DataElements"][4]

testList
Out[62]: "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']"

我能做到的最接近的是使用以下内容,但它在某些字符前留下了一个空格。

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

最佳答案

这就是ast.literal_eval是为了:

>>> from ast import literal_eval
>>>
>>> literal_eval( "['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']")
['Ethnicity', 'Sex', 'Cause of Death', 'Count', 'Percent']

关于python - 将字符串转换回列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33127758/

24 4 0