Python作者 吉多 范罗苏姆 背景 微软
环境管理
uv(推荐) conda
miniconda 清华镜像:
Index of /anaconda/miniconda/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror
Miniconda3-latest-Windows-x86_64.exe
conda --version

添加国内镜像源
# 添加清华镜像频道
conda config --add channels
https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
conda config --add channels
https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
conda config --add channels
https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge
# 搜索时显⽰频道地址
conda config --set show_channel_urls yes
# 移除默认的 defaults 频道(可选,避免仍然请求国外源)
conda config --remove channels defaults
验证是否生效:
conda config --show channels
conda环境管理
# 创建环境并指定 Python 版本
conda create -n myproject python=3.12
# 创建环境并同时安装⼀些包
conda create -n data_env python=3.11 numpy pandas jupyte
# 激活环境
conda activate myproject
# 退出当前环境,回到 base
conda deactivate
# 退出 base 环境
conda deactivate
# 列出所有环境(* 标记当前激活的环境)
conda env list
conda env remove -n myproject #删除环境
# 基于已有环境克隆⼀个新环境
conda create -n myproject_copy --clone myproject
# 安装包(从 conda 仓库)
conda install numpy
conda install numpy=1.26.0 # 指定版本
conda install numpy pandas scipy # 同时安装多个# 从 conda-forge 频道安装
conda install -c conda-forge some-package
# 更新包
conda update numpy
conda update --all # 更新当前环境所有包# 卸载包
conda remove numpy
# 查看当前环境已安装的包
conda list
# 搜索包
conda search numpy
# 导出完整环境(包含平台特定信息,不跨平台)
conda env export > environment.yml
# 导出跨平台配置(只包含⼿动安装的包,推荐)
conda env export --from-history > environment.yml
# 从 yml ⽂件创建新环境
conda env create -f environment.yml
# 更新已有环境(根据 yml ⽂件)
conda env update -f environment.yml --prune #--prune 参数会移除 yml ⽂件中不再列出的包。
name: my_ai_env # 环境的名称
channels: # 下载源(优先级从⾼到低)
- conda-forge
- defaults
dependencies: # 这⾥开始列出依赖
- python=3.10 # 指定 Python 版本
- numpy # 通过 conda 安装
- pandas
- pytorch
- torchvision
- cudatoolkit=11.8 # 只有 conda 能帮你装的底层加速库
- pip: # 在这⾥嵌套写 pip 的依赖
- requests # 通过 pip 安装的包
- sentence-transformers # 假设这是⼀个只有 pip 有的包
- -e . # 甚⾄可以安装本地开发中的项⽬
python基础语法
print("Hello, Python!") #输出语句
pprint("1") #会自动格式化、换行、缩进 主要用于复杂数据结构(列表、字典、嵌套结构)
#整数 python支持无限大的整数
#它⽤内存空间换取了数值范围。 它把整数变成了⼀个可以⾃动扩容的数字容器,只要内存不爆,计算
#就不会溢出。
#python是弱类型语⾔ 可以去,我们声明的⼀个变量,可以随意改它的数据类型。
name = "Tom" # 字符串
age = 18 # 整数
word_potion=80_0000_0000 #大数字可以用下划线分割
height = 1.75 # 浮点数
is_student = True # 布尔值
#浮点数 运算不精准 round() 四舍五入
pi=3.14159
#在 Python 中,理解 None 的关键在于:它不是"零",不是"空字符串",也不是"错误",⽽是
#⼀个表⽰"什么都没有"的实实在在的对象。
#None 的类型是 NoneType 内存中只有⼀个 None 实例。所有的 None 指向的都是同⼀个内存地址。
def say_hello():
print("hello word")
result=say_hello()
print(result) #None
#== 和 is的区别?
#==(等号): 看的是你们的值是不是⼀样的?
#is is看的是,是否是同⼀个内存地址。
print("\n=== ⾝份运算符 is ===")
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(f"a == b → {a == b}") # True(值相同)
print(f"a is b → {a is b}") # False(不是同⼀个对象)
print(f"a is c → {a is c}") # True(c 就是 a,同⼀个对象)
m = 2599
n = 2599
print(m is n) # true #python的上下⽂中,为了性能,会把⼀部分数字提前编译好做缓存。
#为了节省内存。
#Python 中一切皆对象,而对象的属性通常存在 __dict__ 这个字典里
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p = Person("Tom", 18)
print(p.__dict__)
p.__dict__['age'] = 20
print(p.age) # 20
p.__dict__['city'] = "Beijing"
print(p.city) # Beijing
#闭包
#闭包的作⽤域是延⻓作⽤域。
#正常我们⼀个函数,运⾏完,就销毁。
def xxx
xxx()
#运⾏完,函数就销毁了
# list [1, 2, 3] 列表
a= [1, 2, 3];
print(a[0])
print(a[-1]) #最后一个
a.append("orange")
a.insert(1, "grape") # 插入
a.remove("banana") # 删除
a.pop() # 删最后一个
#遍历
for fruit in fruits:
print(fruit)
#dict {"a": 1} 字典
c={"a":1}
print(c.get("a"))
# tuple(1, 2)元组
b=(1,2)
print(b[0])
#set {1, 2, 3} 集合
d = {1, 2, 3}
lst = list(d)
print(lst[1])
#只能包含字母、数字、下划线
#不能以数字开头
#区分大小写
#算术运算符
print(a + b) # 13 加
print(a - b) # 7 减
print(a * b) # 30 乘
print(a / b) # 3.333... 除
print(a // b) # 3 整除
print(a % b) # 1 取余
print(a ** b) # 1000 乘方
#比较运算符
print(a == b) # False 等于
print(a != b) # True 不等于
print(a > b) # True
print(a < b) # False
print(a >= b) # True
#逻辑运算符
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
#字符串
s = "Hello"
print(s[0]) # 'H' 索引
print(s[1:4]) # 'ell' 切片
print(len(s)) # 5 长度
#常用方法
s = " hello world "
print(s.strip()) # 去空格
print(s.upper()) # 转大写
print(s.lower()) # 转小写
print(s.replace("world", "Python")) # 替换
print("hello".split()) # 拆分
#格式化
name = "Tom"
age = 18
# 方式1:f-string(推荐)
print(f"My name is {name}, I'm {age} years old.")
# 方式2:format
print("My name is {}, I'm {} years old.".format(name, age))
#while循环
count = 0
while count < 5:
print(count)
count += 1
#break 和 continue
for i in range(10):
if i == 3:
continue # 跳过 3
if i == 7:
break # 到 7 就停
print(i)
#字典
person = {
"name": "Tom",
"age": 18,
"city": "Beijing"
}
print(person["name"]) # Tom
print(person.get("age")) # 18
person["age"] = 20 # 修改
person["email"] = "tom@xx.com" # 新增
for key, value in person.items():
print(key, value)
#定义函数
def greet(name):
print(f"Hello, {name}!")
greet("Tom")
#定义一个类
class Person:
pass #占位符 这个类现在什么都不做,但它是合法的
p = Person() # 创建一个对象
print(p) # <__main__.Person object at 0x...>
#__init__ ------ 构造方法 self 就是"这个对象自己"
class Person:
count=0
def __init__(self, name, age,balance):
self.name = name
self.age = age
self.__balance = balance #Python 用 双下划线 表示"私有"
def bark(self): # 实例方法
print(f"{self.name} says woof!")
@classmethod #类方法
def get_count(cls): #cls 代表"这个类本身"
return cls.count
@staticmethod #静态方法
def add(a, b): # 跟类和对象都没关系,只是"放在类里归类用"
return a + b
#继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print("...")
class Dog(Animal):
def speak(self):
print(f"{self.name} says woof!")
class Cat(Animal):
def speak(self):
print(f"{self.name} says meow!")
d = Dog("Buddy")
c = Cat("Kitty")
d.speak() # Buddy says woof!
c.speak() # Kitty says meow!
#调用父类
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # 调用父类的 __init__
self.breed = breed
def speak(self):
print(f"{self.name} the {self.breed} says woof!")
d = Dog("Buddy", "Golden Retriever")
d.speak() # Buddy the Golden Retriever says woof!
#@dataclass
#没有dataclass
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name!r}, age={self.age!r})"
def __eq__(self, other):
if not isinstance(other, Person):
return False
return self.name == other.name and self.age == other.age
#用了@dataclass注解后
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int