将带有list语法的字符串转换为list(s)

时间:2014-10-14 14:40:08

标签: python string list csv

我正在尝试将字符串转换为列表。字符串的结构(我有一个充满它们的数据库)总是列表中的n个列表。但是,我有它们的字符串格式。这些数据来自我拥有的大型.csv文件中的一列。

stringOfLists1 = [["Social","Food and Dining","Restaurants","American"]["Social","Food and Dining","Restaurants","Pizza"]]
stringOfLists2 = [["Social","Food and Dining","Restaurants"]]
stringOfLists3 = [[...]]

理想情况下,我希望能够解析每个列表。

listOfLists1
>>> [["Social","Food and Dining","Restaurants","American"]["Social","Food and Dining","Restaurants","Pizza"]]
listOfLists1[0]
>>> ["Social","Food and Dining","Restaurants","American"]
type(listOfLists1)
>>> 'list'
type(listOfLists1[0])
>>> 'list'
type(listOfLists1[0][3])
>>> 'string'
listOfLists1[0][3]
>>> 'American'

我希望我已经彻底解释了这个问题!最后,我试图理解并快速解析数据库中列表的所有元素,但这超出了本问题的范围。谢谢!

1 个答案:

答案 0 :(得分:2)

您正在寻找ast.literal_eval

>>> from ast import literal_eval
>>> stringOfLists1 = '[["Social","Food and Dining","Restaurants","American"], ["Social","Food and Dining","Restaurants","Pizza"]]'
>>> lst = literal_eval(stringOfLists1)
>>> lst
[['Social', 'Food and Dining', 'Restaurants', 'American'], ['Social', 'Food and Dining', 'Restaurants', 'Pizza']]
>>> type(lst)
<class 'list'>
>>> type(lst[0])
<class 'list'>
>>> type(lst[0][3])
<class 'str'>
>>>

它会将每个字符串解析为字符串列表列表,而不会有eval的安全风险。