python经验(持续记录)

** 如何在 IPython/Jupyter Notebook 中调试程序 **

在需要调试的位置前写上

from IPython.core.debugger import Tracer; Tracer()()

即可。运行后会进入PDB调试器,可使用Python PBD命令调试。列出几个常用的命令:

c      continue      运行至断点

n      next             单步调试(不进入子函数)

s       step             进入子函数调试

q       quit            退出调试器

break + 数字     再某一行插入断点

要查看某一变量,直接输入变量名回车即可


** 一个使用 numpy broadcast 机制时,易犯的错误 **

shape 为 (4, 3) 的矩阵

 x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])

与 shape 为 (4,)的矩阵相加会出错

y = np.array([1, 0, 1, 0])
>>> x + y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: operands could not be broadcast together with shapes (4,3) (4,)

反而是和 shape 为 (3,) 的矩阵相加是可以的。

因为一个普通的向量在被扩展为矩阵时,是当作行向量进行重复。

因此,想要重复n次某一列数据时,需要先使用np.reshape(y, (4, 1))把其变成一个4×1的矩阵。注意4×1矩阵和含有4个数的向量是不同的,他们的shape分别是(4,1)和(4,)

猜你喜欢

转载自blog.csdn.net/laowulong350/article/details/79699159