python

Basic

Numpy数组不能直接做判断

  • 如果直接使用np.ndarray类型变量直接做判断语句(如下,b是否有值),则会报错:The true value of an array with more than one element is ambiguous(具有多个元素的数组的真值是不明确的!)

    1
    2
    3
    4
    5
    6
    a = tuple([1,2,3]) #type: tuple 
    b = np.array(a) #type: ndarray
    if a: #can pass
    print(a)
    if b: #raise error
    print(b)
  • 解决方法:将if b——>if b is not None:if list(b)/tuple(b):

argparse模块使用

使用os模块创建文件夹

一般先使用os.path.exists(path)来检查相应文件夹是否存在

  1. 使用os.mkdir(path)创建目录;
  2. 使用os.makedirs(path)递归创建目录;
1
2
if not os.path.exists(path):
os.makedirs(path)

多维数组增加维度

mean_X[:, None]
mean_X[:, np.newaxis]
mean_X = np.expand_dims(mean_X, axis=1)

Develop

python包中__init__.py

  • 将该目录作为Python package的标识;
  • 定义package中的_all_,用于模糊导入;
  • 传送门

sys与os模块

os: This module provides a portable way of using operating system dependent functionality.
sys: This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter.
os模块负责程序与操作系统的交互,提供了访问操作系统底层的接口;sys模块负责程序与python解释器的交互,提供了一系列的函数和变量,用于操控python的运行时环境

Python中dist-packages和site-packages区别

  • sudo apt-get install 安装的package存放在 /usr/lib/python2.7/dist-packages目录中
  • pip 或者 easy_install安装的package存放在/usr/local/lib/python2.7/dist-packages目录
  • 手动从源代码安装的package存放在site-packages目录中;

命令行运行程序可选项:python -h

  • $ python -E file.py:忽略所有PYTHON*环境变量,如PYTHONPATH;
  • $ python -m pdb/ipdb file.py:调试模式;

pdb调试

Common errors

invalid syntax

  • 如果在显示错误处语法正确,请检查前一语句是否漏了括号;
------ 本文结束 ------