python
# 集合操作
unique_values = {1, 2, 3, 3} # 自动去重
unique_values.add(4)
print(unique_values) # {1, 2, 3, 4}
# 冻结集合(不可变集合)
frozen_set = frozenset([1, 2, 3])
python
# 默认字典
from collections import defaultdict
user_data = defaultdict(list)
user_data['Alice'].append('Python')
user_data['Bob'].append('Java')
# 有序字典
from collections import OrderedDict
ordered_dict = OrderedDict([('a', 1), ('b', 2)])
python
# 使用with语句管理文件
with open('data.txt', 'r') as f:
content = f.read()
# 自定义上下文管理器
class FileHandler:
def __init__(self, filename, mode):
self.file = open(filename, mode)
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
with FileHandler('data.txt', 'w') as f:
f.write('Hello, World!')
python
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"错误原因:{e}")
raise ValueError("除数不能为零") from e
finally:
print("资源已释放")
python
# 安装FastAPI与Uvicorn
pip install fastapi uvicorn
# 基础API示例
from fastapi import FastAPI, Query
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
description: str = None
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = Query(None, max_length=50)):
return {"item_id": item_id, "q": q}
@app.post("/items/")
async def create_item(item: Item):
return item
# 启动服务
uvicorn main:app --reload
python
# 创建项目与应用
django-admin startproject myproject
cd myproject
python manage.py startapp core
# 定义模型
from django.db import models
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
# 数据库迁移
python manage.py makemigrations
python manage.py migrate
python
# SQLite示例
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
conn.commit()
conn.close()
# MySQL集成
import mysql.connector
config = {
'user': 'root',
'password': 'password',
'host': 'localhost',
'database': 'mydb'
}
conn = mysql.connector.connect(**config)
python
# asyncio基础
import asyncio
async def fetch_data():
await asyncio.sleep(1)
return {"data": "fetched"}
async def main():
task = asyncio.create_task(fetch_data())
result = await task
print(result)
asyncio.run(main())
python
# pdb调试器
import pdb
def calculate(a, b):
pdb.set_trace() # 设置断点
return a + b
calculate(1, 2)
# cProfile性能分析
import cProfile
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
cProfile.run('fibonacci(30)')
bash
# Git常用命令
git init
git add .
git commit -m "Initial commit"
git remote add origin https://github.com/username/repo.git
git push -u origin main
领域 | 典型场景 | 薪资范围(中国) |
---|---|---|
人工智能 | 深度学习模型开发、自然语言处理 | 30-80 万元 / 年 |
大数据分析 | 实时数据处理、数据可视化 | 20-50 万元 / 年 |
全栈开发 | 前后端分离架构、微服务部署 | 25-60 万元 / 年 |
自动化运维 | DevOps 流程优化、云平台管理 | 18-45 万元 / 年 |
python
# Flask电商后端示例
from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///shop.db'
db = SQLAlchemy(app)
class Product(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
price = db.Column(db.Float, nullable=False)
@app.route('/products', methods=['GET'])
def get_products():
products = Product.query.all()
return jsonify([{'id': p.id, 'name': p.name, 'price': p.price} for p in products])
if __name__ == '__main__':
app.run(debug=True)
python
# FastAPI + TensorFlow示例
from fastapi import FastAPI
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
app = FastAPI()
model = load_model('image_classifier.h5')
@app.post("/predict")
async def predict(image: bytes):
img = Image.open(BytesIO(image)).resize((224, 224))
img_array = np.array(img) / 255.0
prediction = model.predict(np.expand_dims(img_array, axis=0))
return {"class": np.argmax(prediction).tolist()}
pip install
手动安装。venv
或conda
创建隔离环境,避免依赖冲突。flake8
和black
进行代码格式化与检查。通过本指南,你将掌握从基础语法到企业级开发的完整技能链。建议每周投入 10 小时进行代码实践,重点关注项目实战与技术社区互动。Python 的学习没有终点,保持对技术的好奇心,持续关注行业动态,才能在激烈的竞争中脱颖而出。