我刚遇到一个未解决的解决方案;)
我想将字符串放入列表列表。
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]]
感谢
使用ast
库将字符串转换为数据结构:
ast
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