以这种格式提供字符串数组:
stringList = ['(0.0,[0.0,0.0,0.0])\n' , '(1.0,[1.0,0.0,0.0])\n']
如何转换为:
inputs = [0.0 , 1.0]
outputs = [ [0.0,0.0,0.0] , [1.0,0.0,0.0] ]
我最近的是:
inputs = []
outputs = []
for l in stringList :
inputs.append(np.array(float(l.split(',')[0].replace('(' , ''))))
for l in stringList :
outputs.append(float(l.split(',')[1].replace('[' , '')))
print(inputs)
print(outputs)
打印哪些:
[array(0.0), array(1.0)]
[0.0, 1.0]
如何转换为:
inputs = [0.0 , 1.0]
outputs = [ [0.0,0.0,0.0] , [1.0,0.0,0.0] ]
答案 0 :(得分:6)
您的字符串是元组格式。您可以使用ast.literal_eval
将其评估为元组,然后将结果相应地附加到输出:
stringList = ['(0.0,[0.0,0.0,0.0])\n' , '(1.0,[1.0,0.0,0.0])\n']
inputs = []
outputs = []
from ast import literal_eval
for s in stringList:
t = literal_eval(s)
inputs.append(t[0])
outputs.append(t[1])
inputs
# [0.0, 1.0]
outputs
# [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]
或者是较短的版本,您可以在zip
之后使用literal_eval
:
inputs, outputs = zip(*map(literal_eval, stringList))
答案 1 :(得分:0)
其他答案不是pythonic,但这是我的尝试:
<强>代码:强>
stringList = ['(0.0,[0.0,0.0,0.0])\n' , '(1.0,[1.0,0.0,0.0])\n']
inp = []
outp = []
for i in stringList:
x = i.split(',[')[0].replace("(", "").replace("\n", "")
y = i.split(',[')[1].replace("])", "").replace("\n", "").split(',')
z = [float(i) for i in y]
inp.append(float(x))
outp.append(z)
print(inp)
print(outp)
<强>输出:强>
[0.0, 1.0]
[[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]
答案 2 :(得分:0)
Here's another option, using split and some character removal:
import re
inputs = []
outputs = []
for s in stringList:
# delete (, ), [, ], \n characters from string
tmp = re.sub('[\(\)\n\[\]]', '', s)
# first float to inputs, others to outputs
tmp_i, *tmp_o = [float(i) for i in tmp.split(',')]
inputs.append(tmp_i)
outputs.append(tmp_o)
in case you're still using Python 2, change the assignment of tmp_i
and tmp_o
:
tmp_list = [float(i) for i in tmp.split(',')]
inputs.append(tmp_list[0])
outputs.append(tmp_list[1:])
答案 3 :(得分:0)
你可以使用这个
stringList = ['(0.0,[0.0,0.0,0.0])\n' , '(1.0,[1.0,0.0,0.0])\n']
inp_list = map(lambda x: eval(x)[0], stringList)
op_list = map(lambda x: eval(x)[1], stringList)
输出:
print inp_list # [0.0, 1.0]
print op_list # [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]