如何从numpy数组中提取列表?

时间:2019-03-05 15:59:44

标签: python numpy

我得到了以下numpy数组:

array(["['life', 'illusion', 'researcher', 'prove', 'reality', 'doesnt', 'exist', 'youre', 'looking', 'life', 'illusion', 'least', 'quantum', 'level', 'theory', 'recently', 'confirmed', 'set', 'researcher', 'finally', 'mean', 'test', 'john', 'wheeler’s', 'delayedchoice', 'theory', 'concluded', 'physicist', 'right', '1978', 'mr', 'wheeler’s', 'proposed', 'experiment', 'involved', 'moving', 'object', 'given', 'choice', 'act', 'like', 'wave', 'particle', 'former', 'acting', 'vibration', 'frequency', 'distinguish', 'wave', 'latter', 'frequency', 'determine', 'position', 'space', 'unlike', 'wave', 'point', '‘decide’', 'act', 'like', 'one', 'time', 'technology', 'available', 'conduct', 'strong', 'experiment', 'scientist', 'able', 'carry']"])

,并且想知道是否有人知道如何从那里获取字符串列表,例如。 ['life', 'illusion', 'researcher',...]

谢谢

2 个答案:

答案 0 :(得分:3)

不太确定为什么要将此字符串另存为np.array,但是您可以只使用ast.literal_eval

from ast import literal_eval
a = np.array(["['life', 'illusion', 'researcher', 'prove', 'reality..."])

literal_eval(a[0])
# ['life', 'illusion', 'researcher', 'prove', 'reality', 'doesnt...

答案 1 :(得分:2)

您可以分割字符串,然后去除所有多余的字符:

x = np.array(["['life', 'illusion', 'researcher', 'prove', 'reality', 'doesnt', 'exist', 'youre', 'looking', 'life', 'illusion', 'least', 'quantum', 'level', 'theory', 'recently', 'confirmed', 'set', 'researcher', 'finally', 'mean', 'test', 'john', 'wheeler’s', 'delayedchoice', 'theory', 'concluded', 'physicist', 'right', '1978', 'mr', 'wheeler’s', 'proposed', 'experiment', 'involved', 'moving', 'object', 'given', 'choice', 'act', 'like', 'wave', 'particle', 'former', 'acting', 'vibration', 'frequency', 'distinguish', 'wave', 'latter', 'frequency', 'determine', 'position', 'space', 'unlike', 'wave', 'point', '‘decide’', 'act', 'like', 'one', 'time', 'technology', 'available', 'conduct', 'strong', 'experiment', 'scientist', 'able', 'carry']"])

[x.strip("[]'',") for x in x[0].split()]