python

吴龙淼 写于 2023-09-08

环境准备

python版本管理工具

window ps

Invoke-WebRequest -UseBasicParsing -Uri "https://raw.githubusercontent.com/pyenv-win/pyenv-win/master/pyenv-win/install-pyenv-win.ps1" -OutFile "./install-pyenv-win.ps1"; &"./install-pyenv-win.ps1"

pyenv常用命令

pyenv install <version>:安装指定版本的Python。
pyenv uninstall <version>:卸载指定版本的Python。
pyenv versions:列出所有已安装的Python版本,当前全局版本前会有个*号标识。
pyenv global <version>:设置全局的Python版本。
pyenv local <version>:设置当前目录下的Python版本,在当前项目中非常有用。
pyenv shell <version>:仅在当前shell会话中设置Python版本。
pyenv which python:显示将要被执行的python可执行文件的路径。
pyenv rehash:创建或更新shims(让pyenv知道新安装的版本等),在安装新的Python版本后通常需要运行此命令。

包管理工具

pip常用命令

安装特定版本的包 pip install <package_name>==<version>

卸载已安装的包 pip uninstall <package_name>

列出已安装的包 pip list

以更易读的格式显示已安装包及其版本号 pip show <package_name>

列出过时的包(即有新版本可用) pip list --outdated

升级一个已安装的包到最新版本 pip install --upgrade <package_name>

输出当前环境下的所有包及其版本号,通常用于生成 requirements.txt 文件 pip freeze > requirements.txt

根据 requirements.txt 文件安装所有指定的包及其版本 pip install -r requirements.txt
查看包信息

查看当前的配置设置 pip config list

设置镜像源或其他配置项 pip config set global.index-url https://mirrors.aliyun.com/pypi/simple

检查是否存在不兼容的依赖性问题 pip check

常用命令

python -m venv venv 创建虚拟环境
.\venv\Scripts\activate 激活虚拟环境
deactivate 退出虚拟环境

基本类型

虽然是脚本语言,但是不会自动转换类型,需要手动转换

Boolean -> True False
Nothing -> None
Number ->  int float long complex
array ->   list tuple bytearray buffer xrange
object -> Dictionary

api

列表

索引小于0编译成0

# 读
x in list
x not in list (适用有迭代器的str)
list+t
list*n
list[i]
list[i:j]
list[i:j:k]
len(list)
min(list)
max(list)
list.index(x)
list.count(x)

# 写
list[i] = x
list[i:j] <== del list[i:j]
list[i:j:k] <== del list[i:j:k]
list.append(x)
list.clear()
list.copy()
list.extend(t)或list += t
list *= n
list.insert(i,x)
list.pop() list.pop(i)
list.remove(x)
list.(reverse)

字符串

表示方式 单引号: ‘允许包含有 “双” 引号’ 双引号: “允许嵌入 ‘单’ 引号” 三重引号: ‘'’三重单引号’’’, “"”三重双引号”””

集合

创建:
{'','',''}
set([])
set('')

isdisjoint(other) 如果集合中没有与 other 存在交集 返回True
issubset(other) 是否为 other 的子集
issuperset(other) 是否 other 为子集
union(*others) 并集
intersection(*others) 交集
difference(*others) 差集 set - other
symmetric_difference(other) 补集(不包含在交集中)

update(*others)
add(elem)
remove(elem) == discard(elem) 不存在不会抛错
clear()
pop()

映射

创建:
{}, {x: x ** 2 for x in range(10)}
dict([('foo', 100), ('bar', 200)]), dict(foo=100, bar=200)
{'jack': 4098, 'sjoerd': 4127}{}

list(d)
len(d)
d[key] ==  get(key[, default]) 不存在不会报错
d[key] = value
del d[key] == pop(key[, default])不存在不会报错
key in d 如果 d 中存在键 key 则返回 True,否则返回 False。
key not in d === not key in d
clear()
update([other])
d | other 合并,必须都是映射
d |= other other可以是map或者迭代器的键值对

函数

# 测试
def dr_seuss(cat_in_the_hat ='参数默认值', thing1, thing2, *args):
  if cat_in_the_hat == True and
    thing2 == True and
    1900 < year < 2100 and 1 <= month <= 12 and \
    thing2 == None:
  elif cat_in_the_hat != True:
    print 'is cray'
    print 'boring'
  else:
    for arg in args:
    print arg

while

模板字符串

方式一,占位符:

print '打印: {} {}'.format('Whoa.', 'Quite!')

方式二,f-str:
name = "Tom"
age = 3
print(f"他叫 {name}, {age} 岁")

class

class Mammal(object):
  neo_cortex = True

class Cat(Mammal):
  def __init__(self, name, years):
    self.name = name
    self.years = years

  def eat(food):
    print 'nom %s' % (food)

模块化

动态导入,不能导出默认模块,且不需要指定导出内容

导入整个包
import mymodule
mymodule.myfunc()

导入包方法
from mymodule import myvar, myfunc
print myvar
myfunc()

导出空方法,需要加pass避免错误
def myfunc(): pass