分类 Python 下的文章
Miniconda Python虚拟环境管理
简介
Miniconda 是一个 Anaconda 的轻量级替代,默认只包含了 python 和 conda,但是可以通过 pip 和 conda 来安装所需要的包。
安装
Miniconda 安装包可以到 https://mirrors.tuna.tsinghua.edu.cn/anaconda/miniconda/ 下载。
下载后使用命令进行安装
bash Miniconda3-latest-MacOSX-x86_64.sh
如果不需要修改位置,可以一路回车
Conda的环境管理
创建环境
# 创建一个名为python39的环境,指定Python版本是3.9.5(不指定最后版本如 3.9.x,conda会为我们自动寻找3.9.x中的最新版本)
conda create --name py395 python=3.9.5
激活环境
conda activate py395
退出当前环境
conda deactivate
删除环境
# 删除一个已有的环境
conda remove --name py395 --all
查看环境
用户安装的不同Python环境会放在~/miniconda3/envs目录下。查看当前系统中已经安装了哪些环境,使用下面的命令
# 下面三个是相同的
conda info -e
conda env list
conda-env list
Conda的包管理
安装包
默认安装当前环境
# numpy
conda install numpy
# conda会从从远程搜索numpy的相关信息和依赖项目
查看已经安装的库
# 查看已经安装的packages
conda list
# 最新版的conda是从site-packages文件夹中搜索已经安装的包,可以显示出通过各种方式安装的包
查看某个环境的已安装包
# 查看某个指定环境的已安装包
conda list -n py395
搜索package的信息
# 查找package信息
conda search numpy
安装package到指定的环境
# 安装package
conda install -n py395 numpy
# 如果不用-n指定环境名称,则被安装在当前活跃环境
# 也可以通过-c指定通过某个channel安装
更新package
# 更新package
conda update -n py395 numpy
删除package
# 删除package
conda remove -n py35 numpy
更新conda
# 更新conda,保持conda最新
conda update conda
更新anaconda
# 更新anaconda
conda update anaconda
更新Python
conda update python
假设当前环境是python 3.9, conda会将python升级为3.9.x系列的当前最新版本
添加国内镜像地址
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes
也可以根据 https://mirrors.tuna.tsinghua.edu.cn/help/anaconda/ 提供的方法修改家目录的配置文件
Python 3.5 后特性 类型注解
变量类型注解
a: int = 1
# 上面与下面在 pycharm 相同作用
a1 = 1 # type a: int
可以用在函数、类的形参声明上
在IED中使用后会有类型提示。
类型注解,只是注解,不影响实际使用。
也就在函数、类的形参用起来较为人性化
还可以用 typing
模块来加强使用
from typing import List
a: list = [1, 2, 3] # 未使用 typing
b: List[int] = [1, 2, 3] # 使用后可以对列表的内容进行注解
注解后对于协同开发,IDE提示非常友好
自己平时就算了吧。一点都不Python
还有就是函数返回类型声明
def main() -> str:
return "abc"
在pycharm 内可以搞的详细点如下
def main(a: str,
b: str,
c: str) -> List[str]:
"""参数的详细说明,对下面的内容需要有一个空行下面的 type 和上面的类型注解起到一样的作用
:type a: str
:type b: str
:type c: str
:param a: 第一个字符串
:param c: 第二个字符串
:param b: 第三个字符串
"""
return [a, b, c]
if __name__ == '__main__':
main("a", "b", "c")
python 3.8 海象运算符
总结如下:
算是少些一行代码,与多运行一次函数的折中产物
但是同时限定了这个变量的作用域只能在if语言内
对比写法
未使用海象运算符1,多写一行代码
n = len(a)
if n > 10:
print(f"List is too long ({n} elements, expected <= 10)")
未使用海象运算符2,多调用一次函数
if len(a) > 10:
print(f"List is too long ({len(a)} elements, expected <= 10)")
使用海象运算符
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")