Python篇

一、基础语法结构

1. 注释

# 是单行注释

"""
多行注释(文档字符串)
可用于模块、函数、类的说明
"""

'''
这也是多行注释
'''

2. 变量与数据类型

# 变量声明(无需类型声明)
x = 10          # 整数 int
y = 3.14        # 浮点数 float
name = "Alice"  # 字符串 str
is_active = True # 布尔值 bool

# 类型查看
type(x)  # <class 'int'>

# 类型转换
int("123")      # 123
float("3.14")   # 3.14
str(456)        # "456"
bool(0)         # False

3. 基本数据类型详解

Number 数字
# 整数
a = 10
b = 0b1010      # 二进制
c = 0o12        # 八进制
d = 0xA         # 十六进制

# 浮点数
e = 3.14
f = 2e3         # 2000.0

# 复数
g = 3 + 4j

# 运算
x + y           # 加
x - y           # 减
x * y           # 乘
x / y           # 除(浮点数)
x // y          # 整除
x % y           # 取余
x ** y          # 幂运算
abs(x)          # 绝对值
String 字符串
# 创建
s1 = '单引号'
s2 = "双引号"
s3 = """多行
字符串"""
s4 = r"原始字符串\n不转义"

# 常用操作
len(s)                  # 长度
s[0]                    # 索引
s[1:4]                  # 切片 [start:end:step]
s.upper()               # 转大写
s.lower()               # 转小写
s.strip()               # 去两端空格
s.split(',')            # 分割
','.join(list)          # 连接
s.replace('old', 'new') # 替换
s.startswith('pre')     # 判断开头
s.endswith('suf')       # 判断结尾
s.find('sub')           # 查找子串
f"格式化 {x}"           # f-string (Python 3.6+)
List 列表
# 创建
arr = [1, 2, 3]
arr = [0] * 10  # 初始化长度为10的列表
arr = [[0] * 5 for _ in range(3)]  # 二维列表

# 常用操作
arr.append(4)        # 末尾添加 O(1)
arr.pop()           # 末尾删除 O(1)
arr.pop(i)          # 删除索引i的元素 O(n)
arr.insert(i, x)    # 插入 O(n)
arr[i] = x          # 修改 O(1)
x = arr[i]          # 访问 O(1)
len(arr)            # 长度
arr.sort()          # 原地排序 O(n log n)
sorted(arr)         # 返回新列表
arr.reverse()       # 反转
arr.index(x)        # 查找索引 O(n)
x in arr            # 判断是否存在 O(n)

# 切片
arr[start:end:step]
arr[::-1]           # 反转列表
arr[1:3]            # 索引1到2
Tuple 元组
# 创建(不可变)
tup = (1, 2, 3)
tup2 = 1, 2, 3          # 括号可省略
single = (1,)           # 单元素元组需要逗号

# 操作
tup[0]                  # 访问
len(tup)                # 长度
tup.count(1)            # 计数
tup.index(2)            # 查找索引
Dictionary 字典
# 创建
d = {}
d = dict()
d = {'a': 1, 'b': 2}

# 常用操作
d[key] = value      # 添加/修改 O(1)
value = d[key]      # 访问 O(1)
value = d.get(key, default)  # 安全访问,不存在返回默认值
del d[key]          # 删除 O(1)
key in d            # 检查键是否存在 O(1)
d.keys()            # 所有键
d.values()          # 所有值
d.items()           # 所有键值对

# 遍历
for key in d:
for key, value in d.items():
Set 集合
# 创建
s = set()
s = {1, 2, 3}
s = set([1, 2, 3])

# 常用操作
s.add(x)            # 添加 O(1)
s.remove(x)         # 删除,不存在报错 O(1)
s.discard(x)        # 删除,不存在不报错
x in s              # 检查是否存在 O(1)
len(s)              # 大小

# 集合运算
s1 | s2             # 并集
s1 & s2             # 交集
s1 - s2             # 差集
deque 双端队列
from collections import deque

dq = deque()
dq = deque([1, 2, 3])
dq = deque(maxlen=10)  # 固定长度

# 常用操作(全部O(1))
dq.append(x)        # 右端添加
dq.appendleft(x)    # 左端添加
dq.pop()            # 右端删除
dq.popleft()        # 左端删除
dq[0]               # 访问左端
dq[-1]              # 访问右端
defaultdict 默认字典
from collections import defaultdict

# 自动初始化默认值
d1 = defaultdict(int)      # 默认值0
d2 = defaultdict(list)     # 默认值[]
d3 = defaultdict(set)      # 默认值set()
d4 = defaultdict(lambda: 0) # 自定义默认值

# 使用
d = defaultdict(list)
d['key'].append(1)  # 即使'key'不存在也不会报错
Counter 计数器
from collections import Counter

# 创建
c = Counter('abracadabra')  # Counter({'a': 5, 'b': 2, 'r': 2})
c = Counter([1, 2, 1, 3])

# 常用操作
c.most_common(2)    # 出现最多的2个元素
c['a']              # 计数
c['z']              # 不存在返回0,不报错
c.update('abc')     # 更新计数
c.elements()        # 返回迭代器

# 运算
c1 + c2             # 合并计数
c1 - c2             # 相减
heapq 堆
import heapq

# 最小堆
heap = []
heapq.heappush(heap, 3)     # 添加 O(log n)
heapq.heappush(heap, 1)
heapq.heappush(heap, 2)
smallest = heapq.heappop(heap)  # 弹出最小值 O(log n)
heap[0]                 # 查看最小值 O(1)

# 其他操作
heapq.heapify(arr)      # 将列表转为堆 O(n)
heapq.heappushpop(heap, x)  # push后pop
heapq.nlargest(3, arr)  # 最大的3个
heapq.nsmallest(3, arr) # 最小的3个

# 最大堆(通过取负数实现)
heap = []
heapq.heappush(heap, -x)

二、控制流程

1. 条件语句

if condition1:
    # 代码块
elif condition2:
    # 代码块
else:
    # 代码块

# 三元表达式
value = x if condition else y

2. 循环语句

# for循环
for i in range(5):      # 0,1,2,3,4
    print(i)

for item in list:
    print(item)

for key, value in dict.items():
    print(key, value)

# while循环
while condition:
    # 代码块
    if break_condition:
        break           # 跳出循环
    if skip_condition:
        continue        # 跳过本次

# else子句(循环正常结束时执行)
for i in range(5):
    if i == 10:
        break
else:
    print("循环正常结束")

3. 异常处理

try:
    # 可能出错的代码
    result = 10 / 0
except ZeroDivisionError as e:
    # 处理特定异常
    print(f"除零错误: {e}")
except (TypeError, ValueError) as e:
    # 处理多个异常
    print(f"类型或值错误: {e}")
except Exception as e:
    # 处理所有其他异常
    print(f"未知错误: {e}")
else:
    # 无异常时执行
    print("操作成功")
finally:
    # 无论是否异常都执行
    print("清理操作")

三、函数

1. 函数定义

def function_name(param1, param2=default):
    """文档字符串"""
    # 函数体
    return result

# 参数类型
def func(a, b, *args, **kwargs):
    """
    a, b: 位置参数
    *args: 可变位置参数(元组)
    **kwargs: 可变关键字参数(字典)
    """
    pass

# 类型注解(Python 3.5+)
def greet(name: str, times: int = 1) -> str:
    return f"Hello {name}" * times

2. Lambda函数

# 匿名函数
add = lambda x, y: x + y
sorted(lst, key=lambda x: x[1])

3. 作用域

global_var = 10

def func():
    global global_var    # 声明使用全局变量
    local_var = 20
    global_var = 30
    
    def inner():
        nonlocal local_var  # 声明使用外层局部变量
        local_var = 40

四、面向对象编程

1. 类定义

class MyClass:
    """类文档字符串"""
    
    # 类属性
    class_var = "类属性"
    
    def __init__(self, name):
        """构造函数"""
        self.name = name  # 实例属性
        
    def instance_method(self):
        """实例方法"""
        return f"实例方法: {self.name}"
    
    @classmethod
    def class_method(cls):
        """类方法"""
        return f"类方法: {cls.class_var}"
    
    @staticmethod
    def static_method():
        """静态方法"""
        return "静态方法"
    
    @property
    def prop(self):
        """属性装饰器"""
        return self.name.upper()
    
    @prop.setter
    def prop(self, value):
        self.name = value.lower()

2. 继承

class Parent:
    def __init__(self, name):
        self.name = name
    
    def greet(self):
        return f"Hello from {self.name}"

class Child(Parent):
    def __init__(self, name, age):
        super().__init__(name)  # 调用父类方法
        self.age = age
    
    def greet(self):  # 方法重写
        parent_greet = super().greet()
        return f"{parent_greet}, age {self.age}"

# 多重继承
class A:
    pass

class B:
    pass

class C(A, B):  # 继承A和B
    pass

3. 特殊方法(魔术方法)

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __len__(self):
        return 2
    
    def __getitem__(self, index):
        if index == 0:
            return self.x
        elif index == 1:
            return self.y
        else:
            raise IndexError
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

五、模块与包

1. 模块导入

import module_name
import module_name as alias
from module_name import function_name
from module_name import ClassName
from module_name import *
from package.module import something

# 条件导入
try:
    import numpy as np
except ImportError:
    print("NumPy not installed")

# 相对导入(在包内部)
from . import sibling_module
from .. import parent_module
from .subpackage import something

2. 创建模块

# mymodule.py
"""模块文档字符串"""

def my_function():
    """函数文档字符串"""
    pass

class MyClass:
    pass

# 当模块直接运行时执行
if __name__ == "__main__":
    # 测试代码
    print("模块作为脚本运行")

3. 包结构

my_package/
├── __init__.py     # 包初始化文件
├── module1.py
├── module2.py
└── subpackage/
    ├── __init__.py
    └── module3.py

六、文件操作

1. 文件读写

# 传统方式
file = open("file.txt", "r", encoding="utf-8")
content = file.read()
file.close()

# 使用with语句(推荐)
with open("file.txt", "r", encoding="utf-8") as file:
    content = file.read()
    # 自动关闭文件

# 读取方式
content = file.read()           # 读取全部
line = file.readline()          # 读取一行
lines = file.readlines()        # 读取所有行到列表

# 写入方式
with open("output.txt", "w", encoding="utf-8") as file:
    file.write("Hello\n")
    file.writelines(["Line1\n", "Line2\n"])

# 打开模式
# r: 读取(默认)
# w: 写入(覆盖)
# a: 追加
# r+: 读写
# b: 二进制模式

2. 路径操作(使用pathlib,Python 3.4+)

from pathlib import Path

path = Path("folder/file.txt")
path.exists()           # 是否存在
path.is_file()         # 是否是文件
path.is_dir()          # 是否是目录
path.parent            # 父目录
path.name              # 文件名
path.suffix            # 后缀名
path.stem              # 无后缀文件名

# 创建目录
path.mkdir(parents=True, exist_ok=True)

# 遍历目录
for child in path.iterdir():
    print(child)

# 读写文件
content = path.read_text(encoding="utf-8")
path.write_text("content", encoding="utf-8")

七、常用内置模块

1. os模块

import os

os.getcwd()            # 当前工作目录
os.chdir(path)         # 改变目录
os.listdir(path)       # 列出目录内容
os.mkdir(path)         # 创建目录
os.makedirs(path)      # 递归创建目录
os.remove(path)        # 删除文件
os.rmdir(path)         # 删除空目录
os.rename(src, dst)    # 重命名
os.path.join(a, b)     # 路径拼接
os.path.exists(path)   # 路径是否存在

2. sys模块

import sys

sys.argv               # 命令行参数
sys.exit(code)         # 退出程序
sys.path               # Python路径
sys.version            # Python版本
sys.stdin              # 标准输入
sys.stdout             # 标准输出
sys.stderr             # 标准错误

3. datetime模块

from datetime import datetime, date, time, timedelta

now = datetime.now()
today = date.today()

# 格式化
now.strftime("%Y-%m-%d %H:%M:%S")
datetime.strptime("2023-01-01", "%Y-%m-%d")

# 时间计算
tomorrow = today + timedelta(days=1)

4. json模块

import json

# 序列化
json_str = json.dumps(data, indent=2)

# 反序列化
data = json.loads(json_str)

# 文件操作
with open("data.json", "w") as f:
    json.dump(data, f)

with open("data.json", "r") as f:
    data = json.load(f)

Java篇

数组

// 获取数组长度
int len = num.length;    

import java.util.Arrays;

// 数组转字符串
int[] arr = {1, 2, 3};
String str = Arrays.toString(arr);        // "[1, 2, 3]"
String deepStr = Arrays.deepToString(multiArr); // 多维数组

// 填充固定值 
int[] arr = new int[5];
Arrays.fill(arr, 1);          // [1, 1, 1, 1, 1]

// 复制数组
int[] original = {1, 2, 3};
int[] newArray = Arrays.copyOf(original, original.length + 1);    
// newArray = [1, 2, 3, 0] 扩展并补0
int[] shorter = Arrays.copyOf(original, 2);    // shorter = [1, 2] 截断

// 比较数组内容
int[] a = {1, 2, 3};
int[] b = {1, 2, 3};
boolean equal = Arrays.equals(a, b);      // true

// 数组排序(双轴快速排序)
int[] arr = {3, 1, 2};
Arrays.sort(arr);          // [1, 2, 3]

// 二分查找
int[] arr = {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(arr, 3);    // 返回 2
int notFound = Arrays.binarySearch(arr, 6); // 返回负数

字符串

// String类的方法(静态)
String str = "Hello World";
int len = str.length();                            // 获取字符串长度
char ch = str.charAt(2);                           // 获取指定位置字符
String sub1 = str.substring(6);                    // "World" - 截取从索引6到末尾
String sub2 = str.substring(0, 5);                 // "Hello" - 截取从索引0到4
boolean found1 = str.contains("World");            // 是否包含子串
boolean found2 = str.contentEquals("Hello");       // 内容是否相等
boolean empty = str.isEmpty();                     // 是否为空字符串
int index1 = str.indexOf('o');                     // 第一次出现的位置
int index2 = str.lastIndexOf('o');                 // 最后一次出现的位置
int index3 = str.indexOf("World");                 // 子串第一次出现的位置
boolean starts = str.startsWith("Hello");          // 是否以指定字符串开头
boolean ends = str.endsWith("World");              // 是否以指定字符串结尾
String joined = String.join(", ", "A", "B", "C");  // 连接字符串

// 基本数据类型转字符串(适用于所有基本类型和对象)
int num = 123;
String str1 = String.valueOf(num);        // "123"

StringBuilder sb = new StringBuilder();    //该类提供了丰富的方法来操作字符串
sb.append(12);               // 追加数值/字符
sb.insert(2, 'X');           // 在索引2处插入字符X
sb.deleteCharAt(3);          // 删除指定位置的字符
sb.setCharAt(3, 'A');        // 设置指定位置的字符
sb.reverse();                // 反转字符串
String str = sb.toString();  // 转换为String

char[] ch = str.toCharArray();    // 字符串转字符数组
byte[] bytes = str.getBytes();    // 转换为字节数组
Integer.parseInt(123);            // 字符串转int
Double.parseDouble("3.14");       // 字符串转double
Float.parseFloat("2.5");          // 字符串转float
Long.parseLong("123456789");      // 字符串转long
Boolean.parseBoolean("true");     // 字符串转boolean

列表List

List<Integer> result = new ArrayList<>();

Collections.sort(result); // 对集合进行升序排序

// 声明一个存储Integer类型的动态二维数组
List<List<Integer>> arrayList = new ArrayList<>();
arrayList.add(Arrays.asList(7, 8, 9));         // 将数组转化为List后直接传入
arrayList.add(Arrays.asList("x", "y", "z"));

// 声明一个存储数组类型的动态二维数组
List<int[]> arrayList = new ArrayList<>();

// 作为 Java 中最常用的集合接口,提供了丰富的方法来操作列表
result.add(5);                                    // 添加到末尾
result.add(0, 10);                                // 在指定0位置插入
result.remove(0);                                 // 按索引删除
result.clear();                                   // 清空列表
int num = result.get(0);                          // 获取指定位置的元素
int size = result.size();                         // 获取元素个数
boolean empty = result.isEmpty();                 // 判断是否为空
result.set(0, 100);                               // 修改指定位置的元素
boolean has = result.contains(5);                 // 是否包含指定元素
Integer[] array = result.toArray(new Integer[0]); // 转换为数组
list = list.subList(0, 3);                        // 保留索引0到2的元素(前三个),其他的删除

链表LinkedList

LinkedList<Integer> list = new LinkedList<>();

.add(E e)                  // 将元素插入到链表尾部
.push(E e)                 // 将元素插入到链表头部
.add(int index, E element) // 在指定位置插入元素,原位置及之后的元素依次后移
.remove(int index)         // 删除并返回指定位置的元素,空值则默认弹出链表的头部
.removeLast()              // 删除并返回最后一个元素
.clear()                   // 清空链表
.get(int index)            // 获取指定位置的元素
.contains(Object o)        // 判断是否包含指定元素
.set(int index, E element) // 修改指定位置的元素
.size()                    // 返回链表中的元素个数
.isEmpty()                 // 判断链表是否为空
.toArray()                 // 将链表转换为数组

HashMap

// 使用HashMap(最常用,无序)
Map<String, Integer> map = new HashMap<>();

// 添加元素
map.put("apple", 10);
map.put("banana", 5);
map.put("orange", 8);

// 获取值
int apples = map.get("apple");  // 10

// 检查键是否存在
boolean hasApple = map.containsKey("apple");  // true

// 检查值是否存在
boolean hasValue = map.containsValue(10);  // true

//合并键值对:当键不存在时插入新值;当键已存在时,合并新旧值
map.merge(apple, 1, Integer::sum);

// 删除元素
map.remove("banana");

// 大小
int size = map.size();  // 2

// 清空
map.clear();

// 是否为空
boolean isEmpty = map.isEmpty();

// 遍历键
for (String key : map.keySet()) {
    System.out.println(key);
}

// 遍历值
for (Integer value : map.values()) {
    System.out.println(value);
}

// 遍历键值对(推荐)
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

Map<Character, Integer> target = new HashMap<>();
Map<Character, Integer> count = new HashMap<>();
// 填充数据
target.put('a', 1);
count.put('a', 1);
// 比较两个哈希表:key的集合是否相同、每个key对应的value是否相同、Map的大小是否相同
boolean isEqual = target.equals(count);

/**
 * 检查两个Map是否满足以下条件:
 * 1. 键集合完全一致(包含相同的键,不多不少)
 * 2. 对于每个相同的键,map1中的值都要大于等于map2中的对应值
 * 
 * @return 如果满足上述两个条件则返回true,否则返回false
 */
public boolean isKeysEqualAndValuesGreater(Map<Character, Integer> map1, 
                                          Map<Character, Integer> map2) {
    // 使用keySet().equals()方法比较两个Map的键集合
    // 这个检查确保:map1和map2包含完全相同的键
    if (!map1.keySet().equals(map2.keySet())) {
        return false;
    }
    
    // 使用Stream API遍历所有键
    return map1.keySet().stream()
               // 使用allMatch检查是否所有键都满足条件
               // allMatch是一个短路操作,一旦发现不满足条件的键就停止处理
               .allMatch(key -> map1.get(key) >= map2.get(key));
}

Math类(静态,无需创建实例)

int max = Math.max(5, 10);           // 返回 10 ,最大值
int min = Math.min(5, 10);           // 返回 5 ,最小值
int abs1 = Math.abs(-5);             // 返回 5 ,绝对值

double power = Math.pow(2, 3);       // 2的3次方 = 8.0,注意返回的是double类型
double exp = Math.exp(2);            // e的2次方 ≈ 7.389
double log = Math.log(10);           // 自然对数 ln(10)
double log10 = Math.log10(100);      // 以10为底的对数 = 2.0
double sqrt = Math.sqrt(16);         // 平方根 = 4.0
double cbrt = Math.cbrt(27);         // 立方根 = 3.0

double ceil = Math.ceil(3.2);        // 向上取整 = 4.0
double floor = Math.floor(3.8);      // 向下取整 = 3.0
long round = Math.round(3.5);        // 四舍五入 = 4
int roundFloat = Math.round(3.2f);   // 浮点数四舍五入 = 3

double sin = Math.sin(Math.PI/2);    // 正弦 = 1.0
double cos = Math.cos(0);            // 余弦 = 1.0
double tan = Math.tan(Math.PI/4);    // 正切 ≈ 1.0
double asin = Math.asin(1);          // 反正弦
double acos = Math.acos(1);          // 反余弦
double atan = Math.atan(1);          // 反正切

double random = Math.random();       // [0.0, 1.0) 的随机数
double pi = Math.PI;                 // π ≈ 3.141592653589793
double e = Math.E;                   // 自然常数 e ≈ 2.718281828459045

double copySign = Math.copySign(5, -1);  // 返回 -5.0(第一个参数的绝对值,符号同第二个参数)
double signum = Math.signum(-3.5);       // 返回 -1.0(符号函数)
double hypot = Math.hypot(3, 4);         // 返回 sqrt(3² + 4²) = 5.0

特殊知识点

  1. 将字符转换为数值不能直接强转,需要用 (int) (char - '0');将数值转换为字符也不能直接强转,需要用 (char) ('0' + char)
  2. 大写字母的 ASCII 值加 32 就会变为对应的小写字母,反过来小写字母减 32 就会变为大写字母。
  3. 两个相同字母异或的结果为0,不同字母异或的结果为某一值,0和某字母异或的结果还是该字母。
  4. 如果一个字符串 s 可以由它的一个子串重复多次构成,那么将两个原字符串 s 连接起来形成新字符串 s + s ,并移除首尾字符后,原字符串 s 应该仍然出现在这个新字符串中。
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐