Python学习笔记(01)——变量与运算符
语法
命名
命名规则:字母、下划线、数字 组合,但不能以数字开头,且不能是已定义关键字,这与其它常见语言一致(如C、Matlab等等)。
正确:abc1 abc_1 _abc
错误:1abc 1_abc Python
使用方法:无需声明,直接使用,这一点与Matlab相似,与C不同。
区别:
a = 123
b = 123
id(a)
id(b)
随机数
种子的作用
函数: np.random.seed(seed)
总的来说:在哪里使用,每次程序运行至此,产生的随机数就是一样的,比如有一个 test.py
文件,代码如下:
import numpy as np
np.random.seed(2018)
for i in range(3):
print(np.random.random())
print(np.random.random())
print(np.random.randint(1, 10, 3))
print(np.random.randint(1, 10, 3))
运行后总是输出:
0.882349311754
0.10432773786
[6 5 7]
[8 7 7]
0.291960669734
0.742582052944
[7 6 7]
[8 1 8]
0.841348362045
0.163510138002
[5 9 2]
[3 1 9]
可以发现,在此程序段中,每次调用np.random.random()
或 np.random.randint(1, 10, 3)
产生的随机数都不一样,而如果想让每次调用产生的随机数一样,只需要在他们的前面都加上初始化种子操作,且种子相同。即种子在哪,在哪产生固定的随机数,如下面的代码:
import numpy as np
for i in range(3):
np.random.seed(2018)
print(np.random.random())
np.random.seed(2018)
print(np.random.random())
print(np.random.randint(1, 10, 3))
print(np.random.randint(1, 10, 3))
输出为:
0.882349311754
0.882349311754
[3 6 5]
[7 8 7]
0.882349311754
0.882349311754
[3 6 5]
[7 8 7]
0.882349311754
0.882349311754
[3 6 5]
[7 8 7]
转换
字符串到数字
假设有字符串 “11 12 13 100 200”,可以使用以下方法转换:
str = "11 12 100 13 200"
# 方式1
num = [float(x) for x in str.split()]
# 方式2
num = list(map(float, str.split()))
...
第三方库
numpy
- 与python列表不同,通过下标获取的新数组是原始数组的一个视图,所以新数组与原始数组共享同一块内存,如果更改新数组的值,原数组对应的值也会被更改。
- 而通过整数或者bool索引得到的新数组,与原始数组不共享内存,所以更改新数组的值不会更改原始数组的值。
c = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(id(c))
def test(c):
d = c[2:5]
print(c)
print(id(c), id(d))
d[0] = 0
print(c)
return d, c
dd,cc = test(c)
print(id(cc), id(dd))
print(c)
print(cc)
输出结果
140159005936416
[ 1 2 3 4 5 6 7 8 9 10]
(140159005936416, 140159005935936)
[ 1 2 0 4 5 6 7 8 9 10]
(140159005936416, 140159005935936)
[ 1 2 0 4 5 6 7 8 9 10]
[ 1 2 0 4 5 6 7 8 9 10]
包管理器
Pip
本地更新pip
下载好whl格式的pip安装包后执行 python -m pip install pip-9.0.1-py2.py3-none-any.whl
GUI 程序打包成可执行文件
%% 1. For Error: RecursionError: maximum recursion depth exceeded
%% Add "import sys sys.setrecursionlimit(1000000)" in '.spec'
%% 2. For Error: pyinstaller ImportError: cannot import name 'return_future'
pip install tornado==5.1.0
%% 3. For Error: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 130: invalid continuation byte
chcp 65001
%% 4. For Error: "WARNING: file already exists but should not: C:\…\…\…\Local\Temp\_MEI" when run the exe
Add the following codes in '.spec'.
for d in a.datas:
if 'pyconfig' in d[0]:
a.datas.remove(d)
break
%% 5. For Error: ModuleNotFoundError: No module named 'Crypto.Math'
pip uninstall crypto
pip uninstall pycryptodome
pip install pycryptodome
%% 6. For Error: ModuleNotFoundError: No module named 'wx'
pip install -U wxPython
%% 7. For Icon Problem:
%% 1) Add icon resources path in '.spec'
binres = [
('./resources/icons/about.svg', './resources/icons'),
('./resources/icons/about_us.svg', './resources/icons'),
('./resources/icons/close.png', './resources/icons'),
('./resources/icons/close.svg', './resources/icons'),
('./resources/icons/close2.png', './resources/icons'),
...
]
%% 2) Add function getRunningPath() in 'resource.py'
# ------Added by Zhi Liu, begin-----
def getRunningPath():
import os, sys
p = os.path.realpath(sys.path[0])
p = p.replace(r'\base_library.zip', '')
return p
# ------Added by Zhi Liu, end-------
%% 3) Add self.RunningPath in 'ClientWidget.py' and update path of resources
%%
%% Build
pyinstaller -F -w .\ClientWidget.spec
ProblemSolving
无法更新pip或其他包
问题现象:
使用 python -m pip install --upgrade pip
或 pip install --upgrade pip
都无法更新 pip
, 也无法使用 pip
更新其它包。
pkgs$ pip install protobuf-3.0.0-cp27-cp27mu-manylinux1_x86_64.whl
Processing ./protobuf-3.0.0-cp27-cp27mu-manylinux1_x86_64.whl
Collecting six>=1.9 (from protobuf==3.0.0)
Downloading six-1.10.0-py2.py3-none-any.whl
Collecting setuptools (from protobuf==3.0.0)
Downloading setuptools-36.2.7-py2.py3-none-any.whl (477kB)
100% |████████████████████████████████| 481kB 13kB/s
Installing collected packages: six, setuptools, protobuf
Successfully installed protobuf-2.6.1 setuptools-20.7.0 six-1.10.0
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
#--------------------------------------------------------------------------
pkgs$ pip install --upgrade pip
Collecting pip
Using cached pip-9.0.1-py2.py3-none-any.whl
Installing collected packages: pip
Successfully installed pip-8.1.1
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
#--------------------------------------------------------------------------
pkgs$ python -m pip install --upgrade pip
Collecting pip
Using cached pip-9.0.1-py2.py3-none-any.whl
Installing collected packages: pip
Successfully installed pip-8.1.1
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
解决方法:
应该是上次更新 pip 失败,使用 sudo apt remove python-pip
remove错误的包即可。
pkgs$ sudo apt remove python-pip
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
python-pip
0 upgraded, 0 newly installed, 1 to remove and 22 not upgraded.
After this operation, 635 kB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 238955 files and directories currently installed.)
Removing python-pip (8.1.1-2ubuntu0.4) ...
Processing triggers for man-db (2.7.5-1) ...
pkgs$ python -m pip install --upgrade pip
Requirement already up-to-date: pip in /home/liu/.local/lib/python2.7/site-packages
其他包也可以成功更新安装了!!!
版本问题
使用 sys.version_info
来判断程序执行环境,另外对于python2 和 python3,open
返回的类型不一样
f = open(file, 'rb')
if sys.version_info < (3, 1):
sardata = pkl.load(f)
sarplat = pkl.load(f)
# for python3
else:
sardata = pkl.load(f, encoding='latin1')
sarplat = pkl.load(f, encoding='latin1')
加速你的程序
Cython
通过C化加速代码,Cython支持自动C化,也可以用Cython语法自己C化。
Linux下可以直接编译通过,Windows下需要下载安装C++编译工具(如果没装Visual Studio),否则会提示如下错误:
error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
从这里 或这里下载 C++ 编译工具, 安装时按下图选择组件
安装完成后,根据提示需要重启系统,重新编译即可解决。
发布你的库
- 首先需要在 pypi官网注册账号
- 然后在你的包中添加
setup.py
, ````
文件(参考pyaibox)。 - 使用
python setup.py bdist
或python setup.py bdist_wheel
生成发布包 - 使用
twine upload dist/*
上传到pypi。
如果提示如下错误,使用 pip install wheel
安装wheel即可.
>> python setup.py bdist_wheel
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'bdist_wheel'