Numpy Array从Jupyter单元格输出到代码中

时间:2017-11-25 00:27:49

标签: python arrays numpy jupyter-notebook

有没有办法将这个(像这样的jupyter notebook cells输出数组)提供给

[[[[ 54.88135039  71.51893664  60.27633761  54.4883183 ]
   [ 42.36547993  64.58941131  43.75872113  89.17730008]
   [ 96.36627605  38.34415188  79.17250381  52.88949198]
   [ 56.80445611  92.55966383   7.10360582   8.71292997]]

  [[  2.02183974  83.26198455  77.81567509  87.00121482]
   [ 97.86183422  79.91585642  46.14793623  78.05291763]
   [ 11.82744259  63.99210213  14.33532874  94.4668917 ]
   [ 52.18483218  41.466194    26.45556121  77.42336894]]]


 [[[ 45.61503322  56.84339489   1.87898004  61.76354971]
   [ 61.20957227  61.69339969  94.37480785  68.18202991]
   [ 35.95079006  43.70319538  69.76311959   6.02254716]
   [ 66.67667154  67.06378696  21.03825611  12.89262977]]

  [[ 31.54283509  36.37107709  57.01967704  43.86015135]
   [ 98.83738381  10.20448107  20.88767561  16.13095179]
   [ 65.31083255  25.32916025  46.63107729  24.4425592 ]
   [ 15.89695836  11.03751412  65.63295895  13.81829513]]]]
除了执行

之外,

进入np.array()

[[[[ 54.88135039,  71.51893664,  60.27633761,  54.4883183 ],
   [ 42.36547993,  64.58941131,  43.75872113,  89.17730008],
   [ 96.36627605,  38.34415188,  79.17250381,  52.88949198],
   [ 56.80445611,  92.55966383,   7.10360582,   8.71292997]],

  [[  2.02183974,  83.26198455,  77.81567509,  87.00121482],
   [ 97.86183422,  79.91585642,  46.14793623,  78.05291763],
   [ 11.82744259,  63.99210213,  14.33532874,  94.4668917 ],
   [ 52.18483218,  41.466194  ,  26.45556121,  77.42336894]]],


 [[[ 45.61503322,  56.84339489,   1.87898004,  61.76354971],
   [ 61.20957227,  61.69339969,  94.37480785,  68.18202991],
   [ 35.95079006,  43.70319538,  69.76311959,   6.02254716],
   [ 66.67667154,  67.06378696,  21.03825611,  12.89262977]],

  [[ 31.54283509, 36.37107709,  57.01967704,  43.86015135],
   [ 98.83738381, 10.20448107,  20.88767561,  16.13095179],
   [ 65.31083255, 25.32916025,  46.63107729,  24.4425592 ],
   [ 15.89695836, 11.03751412,  65.63295895,  13.81829513]]]]

我使用sublime多个游标来添加逗号,但仍然很痛苦。

编辑:我看到这可以使用REGEX更快地完成,但它需要我在另一个单元格中单独完成。

为什么有人想这样做?

  • 打印变量不再存在
  • 从其他人的笔记本复制阵列时
  • 从导出格式复制数组时

1 个答案:

答案 0 :(得分:0)

您可以使用regex执行此任务。

import re
s = "[[[[ 54.88135039  71.51893664  60.27633761  54.4883183 ]]]"
#replace the white space between two numbers with a comma
s = re.sub('((?<=\d)\s\s(?=\d))', r",\1", s)
#add a comma after each `]`
replaced = re.sub('(](?=\n))', r"\1,", s)

这应该用逗号替换数字之间的所有双白空格,并为所有行添加逗号(在每个]之后)。

编辑:但你为什么要这样做呢?您正在打印一个数组,并希望以后再次使用此打印数组?为什么不简单地使用您正在打印的阵列而不是打印它并解析打印输出?