要在列表中列出的Python字符串

问题描述 投票:-1回答:2

我刚遇到一个未解决的解决方案;)

我想将字符串放入列表列表。

string = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];'
new_string = string.strip().split('=')
# now new_string[1][:-1] does look like a list of lists but everything i tried i just got a string.

也许这里有人知道我如何得到它

data = [[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]]

感谢

python string list
2个回答
4
投票

使用ast库将字符串转换为数据结构:

ast

0
投票

import ast # string is a module in python, to avoid aliasing, use # variable names that ideally don't shadow builtins mystring = r'ABC:=[[0,0,110],[1,0,0,0],[1,0,0,0],[9e+09,9e+09,9e+09,9e+09,9e+09,9e+09]];' # get everything to the right of the = sign, and you don't need the semicolon mystring = mystring.strip().split('=')[-1].rstrip(';') # returns a list mylist = ast.literal_eval(mystring) [[0, 0, 110], [1, 0, 0, 0], [1, 0, 0, 0], [9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0, 9000000000.0]] 也可以正常工作。

eval
© www.soinside.com 2019 - 2024. All rights reserved.