简体   繁体   English

将字符串转换为列表Python

[英]Convert string into list Python

So I've got some data which I scraped from a website and it looks like this: 因此,我从网站上获取了一些数据,看起来像这样:

table = '[['January 2010',1368,719],['February 2010',1366,729] ... ['April 2018',1429,480],['Today',1440,448]]'

It's already formatted pretty well but how would I go about converting this string into a list of lists that looks the exact same but simply has a list datatype instead of string? 它的格式已经很不错了,但是我该如何将这个字符串转换成看起来完全一样但只具有列表数据类型而不是字符串的列表列表呢?

I tried just converting the datatype but that didn't give me the right answer: 我尝试仅转换数据类型,但这没有给我正确的答案:

> print(list(table))
> ['[', '[', "'", 'J', 'a' ... '4', '4', '8', ']', ']']

Thanks in advance 提前致谢

Use ast.literal_eval : 使用ast.literal_eval

In [24]: import ast

In [25]: ast.literal_eval(table)
Out[25]: 
[['January 2010', 1368, 719],
 ['February 2010', 1366, 729],
 ['April 2018', 1429, 480],
 ['Today', 1440, 448]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM