我有一个字符串的形式:
expr="[[1,2,[numpy.sin(x),numpy.cos(x)]],[3,4,[numpy.sin(x)**2,numpy.cos(x)**2]]]"
我想把它转换成一个数组,格式为:
[["1","2",["numpy.sin(x)","numpy.cos(x)"]],["3","4",["numpy.sin(x)**2","numpy.cos(x)**2"]]]
如何做到这一点?我到处都找不到答案
仅根据您在那里的内容,您的表达式看起来就像JSON。假设未来这种类型的值保持不变,那么json
标准模块应该可以满足您的需要。值需要加引号使其成为字符串,否则库可以完成大部分繁重的工作。
import re
import json
expr="[[1,2,[numpy.sin(x),numpy.cos(x)]],[3,4,[numpy.sin(x)**2,numpy.cos(x)**2]]]"
# Quote all the fields.
# expr = [[1,2,[numpy.sin(x),...
# quoted_expr = [["1","2",["numpy.sin(x)",...
quoted_expr = re.sub(r'([^][,]+)([],])', r'"1"2', expr)
# Let the json library take care of the rest.
# my_array = [['1', '2', ['numpy.sin(x)', ...
my_array = json.loads(quoted_expr)