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) # False3. 基本数据类型详解数字类型# 整数 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) # 绝对值字符串# 创建 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# 创建 lst [1, 2, 3] lst2 list(range(5)) # 操作 lst.append(4) # 添加元素 lst.extend([5,6]) # 扩展列表 lst.insert(1, 1.5) # 插入 lst.remove(2) # 移除元素 lst.pop() # 弹出最后一个 lst.pop(0) # 弹出指定索引 lst.index(3) # 查找索引 lst.count(1) # 计数 lst.sort() # 排序 lst.reverse() # 反转 lst.copy() # 浅拷贝 lst.clear() # 清空 # 列表推导式 squares [x**2 for x in range(10)] filtered [x for x in lst if x 0]元组 Tuple# 创建不可变 tup (1, 2, 3) tup2 1, 2, 3 # 括号可省略 single (1,) # 单元素元组需要逗号 # 操作 tup[0] # 访问 len(tup) # 长度 tup.count(1) # 计数 tup.index(2) # 查找索引字典 Dictionary# 创建 d {a: 1, b: 2} d2 dict(a1, b2) # 操作 d[a] # 访问 d.get(c, 0) # 安全访问不存在返回默认值 d[c] 3 # 添加/修改 del d[a] # 删除 d.keys() # 所有键 d.values() # 所有值 d.items() # 所有键值对 d.update({c: 3}) # 更新 d.pop(a) # 弹出指定键 d.clear() # 清空 # 字典推导式 {x: x**2 for x in range(5)}集合 Set# 创建 s {1, 2, 3} s2 set([1, 2, 2, 3]) # {1, 2, 3} # 操作 s.add(4) # 添加 s.remove(1) # 移除不存在会报错 s.discard(1) # 移除不存在不报错 s.pop() # 随机弹出 s.clear() # 清空 # 集合运算 s1 | s2 # 并集 s1 s2 # 交集 s1 - s2 # 差集 s1 ^ s2 # 对称差集二、控制流程1. 条件语句if condition1: # 代码块 elif condition2: # 代码块 else: # 代码块 # 三元表达式 value x if condition else y2. 循环语句# 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, param2default): 文档字符串 # 函数体 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 fHello {name} * times2. Lambda函数# 匿名函数 add lambda x, y: x y sorted(lst, keylambda 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 fHello 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 pass3. 特殊方法魔术方法class Vector: def __init__(self, x, y): self.x x self.y y def __str__(self): return fVector({self.x}, {self.y}) def __repr__(self): return fVector({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 something2. 创建模块# 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, encodingutf-8) content file.read() file.close() # 使用with语句推荐 with open(file.txt, r, encodingutf-8) as file: content file.read() # 自动关闭文件 # 读取方式 content file.read() # 读取全部 line file.readline() # 读取一行 lines file.readlines() # 读取所有行到列表 # 写入方式 with open(output.txt, w, encodingutf-8) as file: file.write(Hello\n) file.writelines([Line1\n, Line2\n]) # 打开模式 # r: 读取默认 # w: 写入覆盖 # a: 追加 # r: 读写 # b: 二进制模式2. 路径操作使用pathlibPython 3.4from 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(parentsTrue, exist_okTrue) # 遍历目录 for child in path.iterdir(): print(child) # 读写文件 content path.read_text(encodingutf-8) path.write_text(content, encodingutf-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(days1)4. json模块import json # 序列化 json_str json.dumps(data, indent2) # 反序列化 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列表ListListInteger result new ArrayList(); Collections.sort(result); // 对集合进行升序排序 // 声明一个存储Integer类型的动态二维数组 ListListInteger arrayList new ArrayList(); arrayList.add(Arrays.asList(7, 8, 9)); // 将数组转化为List后直接传入 arrayList.add(Arrays.asList(x, y, z)); // 声明一个存储数组类型的动态二维数组 Listint[] 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的元素前三个其他的删除链表LinkedListLinkedListInteger 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最常用无序 MapString, 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.EntryString, Integer entry : map.entrySet()) { System.out.println(entry.getKey() : entry.getValue()); } MapCharacter, Integer target new HashMap(); MapCharacter, 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(MapCharacter, Integer map1, MapCharacter, 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特殊知识点将字符转换为数值不能直接强转需要用(int) (char - 0)将数值转换为字符也不能直接强转需要用(char) (0 char)大写字母的 ASCII 值加 32 就会变为对应的小写字母反过来小写字母减 32 就会变为大写字母。两个相同字母异或的结果为0不同字母异或的结果为某一值0和某字母异或的结果还是该字母。如果一个字符串 s 可以由它的一个子串重复多次构成那么将两个原字符串 s 连接起来形成新字符串 s s 并移除首尾字符后原字符串 s 应该仍然出现在这个新字符串中。