Programming Languages Cheat Sheet
Cheat Sheet
多语言数据结构、基本语法和重要API的快速参考指南。
Data Structures
| 特性 | List | Tuple | Set | Dict | Queue | Stack |
|---|---|---|---|---|---|---|
| Syntax | [] | () | {} | {k: v} | Queue() | list |
| Mutability | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ |
| Duplicates | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ |
| Index access | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
| Slicing | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
# List - 可变列表my_list = [1, 2, 3] # 创建列表my_list.append(4) # 添加元素到末尾my_list[1] = 10 # 修改索引为1的元素subset = my_list[1:3] # 切片:获取索引1到3的子列表(不包含3)# Tuple - 不可变元组my_tuple = (1, 2, 3) # 创建元组item = my_tuple[0] # 索引访问# Set - 集合,自动去重my_set = {1, 2, 3} # 创建集合my_set.add(4) # 添加元素union = set1 | set2 # 并集intersection = set1 & set2 # 交集# Dict - 字典,键值对my_dict = {"a": 1, "b": 2} # 创建字典value = my_dict.get("c", 0) # 获取键值,不存在时返回默认值0my_dict["d"] = 4 # 添加或修改键值对keys = my_dict.keys() # 获取所有键| 特性 | Slice | Array | Map | Queue/Stack |
|---|---|---|---|---|
| Syntax | []T | [n]T | map[K]V | slice |
| Mutability | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ✅ |
| Duplicates | ✅ | ✅ | ❌ | ✅ |
| Index access | ✅ | ✅ | ❌ | ✅ |
Go 数据结构语法说明
[]T: Slice(切片),动态数组,长度可变,T 为元素类型[n]T: Array(数组),固定长度数组,n 为长度,T 为元素类型map[K]V: Map(哈希表),K 为键类型,V 为值类型
// Slice - 动态数组,长度可变slice := []int{1, 2, 3} // 创建并初始化 sliceslice = append(slice, 4) // 添加元素到末尾slice[1] = 10 // 修改索引为1的元素subset := slice[1:3] // 切片操作,获取索引1到3的子切片(不包含3)// Array - 固定长度数组,长度不可变arr := [3]int{1, 2, 3} // 创建长度为3的 int 数组arr[0] = 5 // 修改元素// Map - 哈希表,键值对存储m := map[string]int{"a": 1, "b": 2} // 创建并初始化 mapvalue, exists := m["c"] // 通过键获取值和存在状态m["d"] = 4 // 添加或修改键值对delete(m, "a") // 删除键值对// Stack 操作(使用 slice 实现)stack := []int{} // 创建空 stackstack = append(stack, 1) // push:入栈top := stack[len(stack)-1] // peek:查看栈顶元素stack = stack[:len(stack)-1] // pop:出栈// Queue 操作(使用 slice 实现)queue := []int{} // 创建空 queuequeue = append(queue, 1) // enqueue:入队front := queue[0] // peek:查看队首元素queue = queue[1:] // dequeue:出队| 特性 | Array | Object | Set | Map | Queue | Stack |
|---|---|---|---|---|---|---|
| Syntax | [] | {} | new Set() | new Map() | array | array |
| Mutability | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Duplicates | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Index access | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ |
// Array - 数组const arr = [1, 2, 3]; // 创建数组arr.push(4); // 添加元素到末尾arr[1] = 10; // 修改索引为1的元素const subset = arr.slice(1, 3); // 切片:获取索引1到3的子数组(不包含3)arr.forEach(x => console.log(x)); // 遍历数组const mapped = arr.map(x => x * 2); // 映射:对每个元素操作const filtered = arr.filter(x => x > 1); // 过滤:筛选符合条件的元素// Object - 对象const obj = {a: 1, b: 2}; // 创建对象const value = obj.c || 0; // 获取属性,不存在时返回默认值obj.d = 4; // 添加或修改属性const keys = Object.keys(obj); // 获取所有键const values = Object.values(obj); // 获取所有值// Set - 集合,自动去重const set = new Set([1, 2, 2, 3]); // 创建集合set.add(4); // 添加元素set.has(1); // 检查元素是否存在set.delete(1); // 删除元素// Map - 键值对映射const map = new Map([['a', 1], ['b', 2]]); // 创建 mapmap.set('c', 3); // 设置键值对map.get('a'); // 获取值map.has('a'); // 检查键是否存在| 特性 | List | Array | Set | Map | Queue | Stack |
|---|---|---|---|---|---|---|
| Syntax | List | T[] | Set | Map | Queue | Stack |
| Mutability | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Ordered | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ |
| Duplicates | ✅ | ❌ | ❌ | ❌(key) | ✅ | ✅ |
| Index access | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
// List (ArrayList)List<Integer> list = new ArrayList<>();list.add(1);list.add(2);list.set(1, 10);List<Integer> subList = list.subList(0, 2);list.remove(Integer.valueOf(1));// Set (HashSet)Set<Integer> set = new HashSet<>();set.add(1);set.contains(1);set.remove(1);// Map (HashMap)Map<String, Integer> map = new HashMap<>();map.put("a", 1);map.getOrDefault("c", 0);map.containsKey("a");Set<String> keys = map.keySet();// Queue (LinkedList)Queue<Integer> queue = new LinkedList<>();queue.offer(1);Integer front = queue.poll();// Stack (Stack)Stack<Integer> stack = new Stack<>();stack.push(1);Integer top = stack.pop();Integer peek = stack.peek();| 特性 | Table(Array) | Table(Dict) |
|---|---|---|
| Syntax | {} | {} |
| Mutability | ✅ | ✅ |
| Ordered | ✅ | ❌ |
| Duplicates | ✅ | ❌(key) |
| Index access | ✅ | ❌ |
-- Table as Arrayarr = {1, 2, 3}table.insert(arr, 4)arr[2] = 10table.remove(arr, 1)-- Table as Dictionarydict = {a = 1, b = 2}dict["c"] = 3dict.d = 4value = dict.a or 0-- Common table operationscount = #arrfor i, v in ipairs(arr) do print(i, v)endfor k, v in pairs(dict) do print(k, v)endBasic Syntax
Common Syntax
# Variables - 变量声明x = 10 # 整数name = "Python" # 字符串is_active = True # 布尔值# Operators - 运算符+, -, *, /, //, %, ** # 加减乘除、整除、取模、幂运算==, !=, >, <, >=, <= # 比较运算符and, or, not # 逻辑运算符in, is # 成员检测、身份检测# Functions - 函数定义def greet(name): return f"Hello, {name}"// Variables - 变量声明var x int = 10 // 完整声明var name string = "Go"isActive := true // 短变量声明(自动推导类型)// Operators - 运算符+, -, *, /, % // 算术运算符==, !=, >, <, >=, <= // 比较运算符&&, ||, ! // 逻辑运算符// Functions - 函数定义func greet(name string) string { // 参数类型和返回值类型 return fmt.Sprintf("Hello, %s", name)}// Variables - 变量声明let x = 10; // 可变变量const name = "JavaScript"; // 不可变常量let isActive = true; // 布尔值// Operators - 运算符+, -, *, /, % // 算术运算符==, ===, !=, !==, >, <, >=, <= // 比较运算符(== 值比较,=== 类型+值比较)&&, ||, ! // 逻辑运算符in, instanceof // 成员检测、类型检测// Functions - 函数定义function greet(name) { return `Hello, ${name}`;}// Variables - 变量声明int x = 10; // int 类型String name = "Java"; // 字符串类型boolean isActive = true; // 布尔类型// Operators - 运算符+, -, *, /, % // 算术运算符==, !=, >, <, >=, <= // 比较运算符&&, ||, ! // 逻辑运算符instanceof // 类型检测// Methods - 方法定义public String greet(String name) { return "Hello, " + name;}-- Variables - 变量声明globalVar = 10 -- 全局变量local localVar = 20 -- 局部变量(推荐使用)local name = "Lua"local isActive = true-- Operators - 运算符+, -, *, /, %, ^ -- 算术运算符(^ 为幂运算)==, ~=, >, <, >=, <= -- 比较运算符(~= 为不等于)and, or, not -- 逻辑运算符-- Functions - 函数定义function greet(name) return "Hello, " .. name -- .. 为字符串拼接endControl Flow
Conditional Statements
# If-elif-elseif condition: passelif condition2: passelse: pass# Ternary operatorresult = "yes" if condition else "no"# Nested conditionsif outer_condition: if inner_condition: pass else: pass// If-else if-elseif condition {} else if condition2 {} else {}// If with initializationif x := getValue(); x > 0 { fmt.Println("positive")} else { fmt.Println("non-positive")}// Switch statementswitch value {case 1: fmt.Println("one")case 2: fmt.Println("two")default: fmt.Println("other")}// If-else if-elseif (condition) {} else if (condition2) {} else {}// Ternary operatorresult = condition ? "yes" : "no";// Switch statementswitch (value) { case 1: console.log("one"); break; case 2: console.log("two"); break; default: console.log("other");}// If-else if-elseif (condition) {} else if (condition2) {} else {}// Ternary operatorresult = condition ? "yes" : "no";// Switch statementswitch (value) { case 1: System.out.println("one"); break; case 2: System.out.println("two"); break; default: System.out.println("other");}// Switch expressions (Java 14+)String message = switch (value) { case 1 -> "one"; case 2 -> "two"; default -> "other";};-- If-elseif-elseif condition thenelseif condition2 thenelseend-- Nested conditionsif outer_condition then if inner_condition then else endend-- No ternary operator in Lua-- Use if-else or logical operatorsresult = condition and "yes" or "no"Loop Statements
# For loop with rangefor i in range(10): # 0 to 9 passfor i in range(1, 11): # 1 to 10 passfor i in range(0, 10, 2): # 0, 2, 4, 6, 8 pass# For loop over iterablefor item in items: passfor index, item in enumerate(items): pass# While loopwhile condition: pass# Loop controlfor i in range(10): if i == 5: break # Exit loop if i == 3: continue # Skip to next iteration// Traditional for loopfor i := 0; i < 10; i++ {}// For range over slice/arrayfor index, item := range items {}// For range over mapfor key, value := range m {}// While loop (Go only has for)for condition {}// Infinite loopfor {}// Loop controlfor i := 0; i < 10; i++ { if i == 5 { break // Exit loop } if i == 3 { continue // Skip to next iteration }}// Traditional for loopfor (let i = 0; i < 10; i++) {}// For...of loop (iterables)for (const item of items) {}// For...in loop (object properties)for (const key in obj) {}// While loopwhile (condition) {}// Do-while loopdo {} while (condition);// Loop controlfor (let i = 0; i < 10; i++) { if (i === 5) { break; // Exit loop } if (i === 3) { continue; // Skip to next iteration }}// Traditional for loopfor (int i = 0; i < 10; i++) {}// Enhanced for loopfor (int item : items) {}// While loopwhile (condition) {}// Do-while loopdo {} while (condition);// Loop controlfor (int i = 0; i < 10; i++) { if (i == 5) { break; // Exit loop } if (i == 3) { continue; // Skip to next iteration }}// Labeled loops (for nested loops)outer: for (int i = 0; i < 3; i++) { inner: for (int j = 0; j < 3; j++) { if (i == 1 && j == 1) { break outer; // Exit outer loop } }}-- Numeric for loopfor i = 1, 10 do -- 1 to 10endfor i = 1, 10, 2 do -- 1, 3, 5, 7, 9end-- Generic for loop (ipairs for arrays)for i, v in ipairs(arr) doend-- Generic for loop (pairs for dictionaries)for k, v in pairs(dict) doend-- While loopwhile condition doend-- Repeat until loop (like do-while)repeatuntil condition-- Loop controlfor i = 1, 10 do if i == 5 then break -- Exit loop end if i == 3 then -- No continue in Lua, use if endendLanguage-Specific Syntax
# Lambda - 匿名函数add = lambda x, y: x + y# Classes - 类定义class Person: def __init__(self, name): # 构造函数 self.name = name def greet(self): # 实例方法 return f"Hello, {self.name}"# List Comprehension - 列表推导式squared = [x**2 for x in range(10)] # 生成0-9的平方数列表// Multiple return values - 多返回值func divide(a, b int) (int, error) { // 返回结果和错误 if b == 0 { return 0, errors.New("division by zero") // 返回错误 } return a / b, nil // 返回结果,错误为 nil}// Structs - 结构体type Person struct { Name string // 结构体字段 Age int}func (p Person) Greet() string { // 方法(值接收者) return fmt.Sprintf("Hello, %s", p.Name)}// Goroutines - 协程go func() { // go 关键字启动协程 fmt.Println("goroutine")}()// Channels - 通道(协程间通信)ch := make(chan int) // 创建通道go func() { ch <- 1 // 发送数据到通道}()value := <-ch // 从通道接收数据// Ternary - 三元运算符result = condition ? a : b;// Arrow Function - 箭头函数const greet = (name) => `Hello, ${name}`;// Objects - 对象定义const person = { name: "John", greet() { // 对象方法 return `Hello, ${this.name}`; }};// Array methods - 数组方法items.forEach(item => console.log(item)); // 遍历数组const mapped = items.map(x => x * 2); // 映射数组const filtered = items.filter(x => x > 1); // 过滤数组// Ternary - 三元运算符result = condition ? a : b;// Classes - 类定义public class Person { private String name; public Person(String name) { // 构造方法 this.name = name; } public String greet() { return "Hello, " + name; }}// Lambda - Lambda 表达式Runnable r = () -> System.out.println("Hello");Predicate<Integer> isEven = x -> x % 2 == 0;List<Integer> evens = list.stream() .filter(isEven) // Stream API 过滤 .collect(Collectors.toList()); // 收集为 Listlocal greet = function(name) -- 匿名函数 return "Hello, " .. nameend-- Multiple return values - 多返回值function getCoordinates() return 10, 20endlocal x, y = getCoordinates() -- 接收多个返回值-- Tables as objects - table 作为对象使用local person = { name = "John", greet = function(self) return "Hello, " .. self.name end}person:greet() -- 调用方法Functions & Parameter Passing
Function Definition & Calling
# Function definitiondef greet(name, age=25): return f"Hello {name}, you are {age} years old"# Positional argumentsresult = greet("Alice", 30)# Keyword argumentsresult = greet(name="Bob", age=35)# Default argumentsresult = greet("Charlie") # Uses default age=25# Variable argumentsdef func(*args, **kwargs): print(args) # Tuple of positional args print(kwargs) # Dict of keyword argsfunc(1, 2, 3, name="Alice", age=25)// Function definitionfunc greet(name string, age int) string { return fmt.Sprintf("Hello %s, you are %d years old", name, age)}// Named return valuesfunc calculate(a, b int) (sum, diff int) { sum = a + b diff = a - b return // Returns named variables}// Variadic functionfunc sum(numbers ...int) int { total := 0 for _, num := range numbers { total += num } return total}result := greet("Alice", 30)total := sum(1, 2, 3, 4, 5)// Function declarationfunction greet(name, age = 25) { return `Hello ${name}, you are ${age} years old`;}// Arrow functionconst greetArrow = (name, age = 25) => `Hello ${name}, you are ${age} years old`;// Rest parametersfunction func(...args) { console.log(args); // Array of arguments}// Destructuring parametersconst greetPerson = ({name, age}) => `Hello ${name}, age ${age}`;result = greet("Alice", 30);func(1, 2, 3, "hello");// Method definitionpublic String greet(String name, int age) { return String.format("Hello %s, you are %d years old", name, age);}// Method overloadingpublic String greet(String name) { return greet(name, 25); // Calls other method with default age}// Varargs methodpublic int sum(int... numbers) { int total = 0; for (int num : numbers) { total += num; } return total;}String result = greet("Alice", 30);int total = sum(1, 2, 3, 4, 5);-- Function definitionfunction greet(name, age) age = age or 25 -- Default value return "Hello " .. name .. ", you are " .. age .. " years old"end-- Multiple return valuesfunction getPerson() return "Alice", 30end-- Variable argumentsfunction sum(...) local total = 0 for i, v in ipairs({...}) do total = total + v end return totalendresult = greet("Alice", 30)name, age = getPerson() -- Multiple assignmenttotal = sum(1, 2, 3, 4, 5)Parameter Passing Mechanisms
| Type | Passing Mechanism | Behavior |
|---|---|---|
| Immutable (int, str, tuple) | Pass by object reference | Cannot modify original |
| Mutable (list, dict, set) | Pass by object reference | Can modify original content |
| Objects | Pass by object reference | Can modify object attributes |
# Immutable types - cannot modify originaldef modify_int(x): x = 10 # Only modifies local copy return xnum = 5result = modify_int(num) # num is still 5# Mutable types - can modify originaldef modify_list(lst): lst.append(4) # Modifies original list return lstmy_list = [1, 2, 3]modify_list(my_list) # my_list is now [1, 2, 3, 4]# To avoid modifying mutable typesdef safe_modify(lst): new_lst = lst.copy() # Create copy new_lst.append(4) return new_lst| Type | Passing Mechanism | Behavior |
|---|---|---|
| All types | Pass by value | Copies value to function |
| Pointers | Pass by reference | Can modify original via pointer |
| Slices/Maps/Channels | Pass by value (reference types) | Copy header, can modify underlying data |
// Value types - pass by copyfunc modifyInt(x int) { x = 10 // Only modifies local copy}num := 5modifyInt(num) // num is still 5// Pointer types - pass by referencefunc modifyIntPtr(x *int) { *x = 10 // Modifies original value}num := 5modifyIntPtr(&num) // num is now 10// Reference types (slice, map, channel)func modifySlice(s []int) { s[0] = 10 // Modifies underlying array s = append(s, 4) // Only modifies local slice header}slice := []int{1, 2, 3}modifySlice(slice) // slice[0] is now 10, but length unchanged| Type | Passing Mechanism | Behavior |
|---|---|---|
| Primitives (number, string, boolean) | Pass by value | Copies value to function |
| Objects (including arrays, functions) | Pass by reference | Can modify original object |
// Primitive types - pass by valuefunction modifyNum(x) { x = 10; // Only modifies local copy return x;}let num = 5;modifyNum(num); // num is still 5// Object types - pass by referencefunction modifyArray(arr) { arr.push(4); // Modifies original array return arr;}let myArray = [1, 2, 3];modifyArray(myArray); // myArray is now [1, 2, 3, 4]// To avoid modifying objectsfunction safeModifyArray(arr) { const newArr = [...arr]; // Create copy newArr.push(4); return newArr;}| Type | Passing Mechanism | Behavior |
|---|---|---|
| Primitives (int, double, boolean, etc.) | Pass by value | Copies value to method |
| Objects (including arrays) | Pass by value (reference) | Copies reference, can modify object |
// Primitive types - pass by valuepublic void modifyInt(int x) { x = 10; // Only modifies local copy}int num = 5;modifyInt(num); // num is still 5// Object types - pass by reference valuepublic void modifyArray(List<Integer> list) { list.add(4); // Modifies original list list = new ArrayList<>(); // Only modifies local reference}List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3));modifyArray(myList); // myList is now [1, 2, 3, 4]// To avoid modifying objectspublic void safeModifyArray(List<Integer> list) { List<Integer> newList = new ArrayList<>(list); // Create copy newList.add(4);}| Type | Passing Mechanism | Behavior |
|---|---|---|
| All types | Pass by reference | Tables passed by reference, others by value |
-- Numbers/strings - pass by valuefunction modifyNum(x) x = 10 -- Only modifies local copy return xendlocal num = 5modifyNum(num) -- num is still 5-- Tables - pass by referencefunction modifyTable(tbl) tbl.value = 10 -- Modifies original table return tblendlocal myTable = {value = 5}modifyTable(myTable) -- myTable.value is now 10-- To avoid modifying tablesfunction safeModifyTable(tbl) local newTbl = {} for k, v in pairs(tbl) do newTbl[k] = v end newTbl.value = 10 return newTblendHigher-Order Functions & Closures
# Higher-order functiondef apply_operation(func, numbers): return [func(x) for x in numbers]# Lambda functionssquare = lambda x: x ** 2result = apply_operation(square, [1, 2, 3, 4])# Closuresdef make_multiplier(factor): def multiplier(x): return x * factor # Captures factor from outer scope return multipliertimes_three = make_multiplier(3)result = times_three(5) # Returns 15# Decorators (higher-order functions)def timer(func): import time def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) print(f"Function took {time.time() - start} seconds") return result return wrapper@timerdef slow_function(): time.sleep(1) return "Done"// Higher-order functionfunc applyOperation(func func(int) int, numbers []int) []int { result := make([]int, len(numbers)) for i, num := range numbers { result[i] = func(num) } return result}// Function literals (closures)func main() { square := func(x int) int { return x * x } result := applyOperation(square, []int{1, 2, 3, 4}) // Closure capturing outer variable factor := 3 multiplier := func(x int) int { return x * factor } result2 := applyOperation(multiplier, []int{1, 2, 3, 4})}// Higher-order functionfunction applyOperation(func, numbers) { return numbers.map(func);}// Arrow functionsconst square = x => x ** 2;const result = applyOperation(square, [1, 2, 3, 4]);// Closuresfunction makeMultiplier(factor) { return function(x) { return x * factor; // Captures factor from outer scope };}const timesThree = makeMultiplier(3);const result2 = timesThree(5); // Returns 15// Function methods (bind, call, apply)const person = {name: "Alice"};function greet(greeting) { return `${greeting}, ${this.name}`;}const boundGreet = greet.bind(person);boundGreet("Hello"); // "Hello, Alice"// Functional interfaces (Java 8+)import java.util.function.*;import java.util.stream.Collectors;// Higher-order function using streamsList<Integer> applyOperation(Function<Integer, Integer> func, List<Integer> numbers) { return numbers.stream() .map(func) .collect(Collectors.toList());}// Lambda expressionsFunction<Integer, Integer> square = x -> x * x;List<Integer> result = applyOperation(square, Arrays.asList(1, 2, 3, 4));// Closures (effectively final variables)public Function<Integer, Integer> makeMultiplier(int factor) { return x -> x * factor; // Captures factor (must be effectively final)}Function<Integer, Integer> timesThree = makeMultiplier(3);int result2 = timesThree.apply(5); // Returns 15// Method referencesList<String> names = Arrays.asList("Alice", "Bob", "Charlie");List<Integer> nameLengths = names.stream() .map(String::length) // Method reference .collect(Collectors.toList());-- Higher-order functionfunction applyOperation(func, numbers) local result = {} for i, num in ipairs(numbers) do result[i] = func(num) end return resultend-- Anonymous functionslocal square = function(x) return x * x endlocal result = applyOperation(square, {1, 2, 3, 4})-- Closuresfunction makeMultiplier(factor) return function(x) return x * factor -- Captures factor from outer scope endendlocal timesThree = makeMultiplier(3)local result2 = timesThree(5) -- Returns 15-- Functions as first-class citizenslocal functions = { add = function(a, b) return a + b end, multiply = function(a, b) return a * b end}local sum = functions.add(5, 3)Important APIs
String Operations
s = "hello"s.upper() # 转大写s.lower() # 转小写s.strip() # 去除首尾空格s.split(',') # 分割字符串s.startswith('prefix') # 检查前缀s.endswith('suffix') # 检查后缀s.replace('old', 'new') # 替换子串s := "hello"strings.ToUpper(s) // 转大写strings.ToLower(s) // 转小写strings.TrimSpace(s) // 去除首尾空格strings.Split(s, ",") // 分割字符串strings.HasPrefix(s, "prefix") // 检查前缀strings.HasSuffix(s, "suffix") // 检查后缀strings.Replace(s, "old", "new", -1) // 替换子串const s = "hello";s.toUpperCase(); // 转大写s.toLowerCase(); // 转小写s.trim(); // 去除首尾空格s.split(','); // 分割字符串s.startsWith('prefix'); // 检查前缀s.endsWith('suffix'); // 检查后缀s.replace('old', 'new'); // 替换子串String s = "hello";s.toUpperCase(); // 转大写s.toLowerCase(); // 转小写s.trim(); // 去除首尾空格s.split(","); // 分割字符串s.startsWith("prefix"); // 检查前缀s.endsWith("suffix"); // 检查后缀s.replace("old", "new"); // 替换子串s = "hello"string.upper(s) -- 转大写string.lower(s) -- 转小写string.gsub(s, "pattern", "replacement") -- 替换模式string.find(s, "pattern") -- 查找模式string.sub(s, 1, 3) -- 截取子串string.format("%s %d", "hello", 42) -- 格式化字符串File I/O
with open('file.txt', 'r') as f: content = f.read() # 读取文件with open('file.txt', 'w') as f: f.write('content') # 写入文件from pathlib import Pathpath = Path('file.txt')path.exists() # 检查路径path.read_text() # 读取文件内容content, err := os.ReadFile("file.txt") // 读取文件os.WriteFile("file.txt", []byte("content"), 0644) // 写入文件os.Stat("file.txt") // 获取文件信息os.ReadDir(".") // 列出目录内容os.Mkdir("dir", 0755) // 创建目录fetch('file.txt') .then(res => res.text()) // 读取文件// 写入文件需要使用 File APIconst file = new File(["content"], "file.txt");Files.readString(Path.of("file.txt")); // 读取文件Files.writeString(Path.of("file.txt"), "content"); // 写入文件Files.exists(Path.of("file.txt")); // 检查文件是否存在local file = io.open("file.txt", "r") -- 打开文件读取local content = file:read("*a") -- 读取全部内容file:close()local file = io.open("file.txt", "w") -- 打开文件写入file:write("content") -- 写入内容file:close()os.remove("file.txt") -- 删除文件JSON Processing
import jsonjson.dumps(obj) # 对象转 JSON 字符串json.loads(json_str) # JSON 字符串转对象json.Marshal(obj) // 对象转 JSON 字节json.Unmarshal(data, &obj) // JSON 字节转对象JSON.stringify(obj); // 对象转 JSON 字符串JSON.parse(jsonStr); // JSON 字符串转对象// JacksonObjectMapper mapper = new ObjectMapper();String json = mapper.writeValueAsString(obj); // 对象转 JSONMyClass obj = mapper.readValue(json, MyClass.class); // JSON 转对象HTTP Requests
import requestsresponse = requests.get('https://api.example.com')data = response.json() # 解析 JSON 响应resp, err := http.Get("https://api.example.com")defer resp.Body.Close()body, _ := ioutil.ReadAll(resp.Body)fetch('https://api.example.com') .then(res => res.json()) .then(data => console.log(data));HttpClient client = HttpClient.newHttpClient();HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("https://api.example.com")) .build();HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());Date/Time
from datetime import datetimenow = datetime.now()formatted = now.strftime('%Y-%m-%d') # 格式化日期now := time.Now()formatted := now.Format("2006-01-02") // 格式化日期(Go 特殊格式)const now = new Date();const formatted = now.toISOString(); // 转为 ISO 字符串LocalDateTime now = LocalDateTime.now();String formatted = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));os.time() -- 获取当前时间戳os.date() -- 格式化日期Random & Math
import randomrandom.randint(1, 10) # 随机整数 [1, 10]random.choice(['a', 'b', 'c']) # 随机选择rand.Intn(10) // 随机整数 [0, 10)rand.Intn(len(arr)) // 随机索引Math.random(); // 随机数 [0, 1)Math.floor(Math.random() * 10); // 随机整数 [0, 10)Math.max(1, 2, 3); // 最大值math.random(1, 10) -- 随机整数 [1, 10]math.floor(3.14) -- 向下取整math.ceil(3.14) -- 向上取整math.max(1, 2, 3) -- 最大值Collections (Array/List/Table)
arr = [1, 2, 3]arr.append(4) # 添加到末尾arr.remove(1) # 删除元素1 in arr # 检查元素是否存在arr.index(2) # 查找元素索引[x for x in arr if x > 1] # 列表推导// Slicearr := []int{1, 2, 3}arr = append(arr, 4) // 添加到末尾// Mapm := make(map[string]int)m["key"] = 1 // 添加键值对val, ok := m["key"] // 获取值arr = [1, 2, 3]arr.push(4); // 添加到末尾arr.pop(); // 删除末尾元素arr.shift(); // 删除首元素arr.includes(2); // 检查元素是否存在arr.indexOf(2); // 查找元素索引arr.filter(x => x > 1); // 过滤数组arr.map(x => x * 2); // 映射数组arr.reduce((acc, x) => acc + x, 0); // 归约// ArrayListList<Integer> list = new ArrayList<>();list.add(1); // 添加元素list.remove(Integer.valueOf(1)); // 删除元素(按值)list.contains(1); // 检查元素是否存在list.get(0); // 获取元素// HashMapMap<String, Integer> map = new HashMap<>();map.put("key", 1); // 添加键值对map.get("key"); // 获取值map.containsKey("key"); // 检查键是否存在-- Tablearr = {1, 2, 3}table.insert(arr, 1, value) -- 在索引1处插入值table.remove(arr, 1) -- 删除索引1的元素table.sort(arr) -- 排序table.concat(arr, ",") -- 连接为字符串table.unpack(arr) -- 解包Async Operations
import asyncioasync def fetch_data(): async with aiohttp.ClientSession() as session: async with session.get('url') as response: return await response.json()asyncio.run(fetch_data())ch := make(chan int)go func() { ch <- 1 // 发送数据到通道}()select { // 多路复用case v := <-ch: fmt.Println(v) // 接收数据case <-time.After(time.Second): fmt.Println("timeout") // 超时}// PromisePromise.resolve(1).then(x => console.log(x));// Async/Awaitasync function fetchData() { const res = await fetch('url'); const data = await res.json(); return data;}// setTimeoutsetTimeout(() => console.log('delayed'), 1000);Programming Languages Cheat Sheet

