将字符串转换为python中的列表列表

时间:2019-02-28 06:27:29

标签: python

    I have a string like below I would like to convert this string into list of lists:

issues = '[ [this is not a good book as i told ] ,
            [we are going to book shop to buy good books], 
            [I bought one good book for you] ]'

我已经在下面的代码中尝试过此错误:

import ast
result = ast.literal_eval(issues)
result

Error:

Traceback (most recent call last):

  File "C:\ProgramData\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2961, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)

  File "<ipython-input-86-ef20f1c8417e>", line 2, in <module>
    result2 = ast.literal_eval(result2)

  File "C:\ProgramData\Anaconda3\lib\ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')

  File "C:\ProgramData\Anaconda3\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)

期望如下所示的输出作为列表列表:

result = [ [this is not a good book as i told ], 
           [we are going to book shop to buy good books], 
           [I bought one good book for you] ]

提前谢谢...。

2 个答案:

答案 0 :(得分:0)

issues = '[ [this is not a good book as i told ] ,[we are going to book shop to buy good books], [I bought one good book for you] ]'

a = [i for i in issues.replace("[","").replace("]","").split(',')]
l=[]
for i in range(len(a)):
    f= []
    f.append(a[i])
    l.append(f)

print l

答案 1 :(得分:0)

您可能除了以下输出: [[''这不是一本好书,'],['我们要去书店买好书,],['我为你买了一本好书]]

下面是代码:

重新导入

问题='[[这不是我告诉过的好书] [我们要去书店购买好书] [我为您买了一本好书]]'

step_1 = re.sub('[+ [','',问题)

step_2 = re.sub('] + [',',',step_1)

step_3 = re.sub('] +]','',step_2)

print([[step_3.split(',')]中[i的i [s.strip()])