placeholderProgramming Languages Cheat Sheet

Programming Languages Cheat Sheet

Cheat Sheet

多语言数据结构、基本语法和重要API的快速参考指南。

Data Structures

特性ListTupleSetDictQueueStack
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()         # 获取所有键
特性SliceArrayMapQueue/Stack
Syntax[]T[n]Tmap[K]Vslice
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:出队
特性ArrayObjectSetMapQueueStack
Syntax[]{}new Set()new Map()arrayarray
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');                          // 检查键是否存在
特性ListArraySetMapQueueStack
SyntaxListT[]SetMapQueueStack
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)end

Basic Syntax

Common Syntax

# Variables - 变量声明x = 10                      # 整数name = "Python"             # 字符串is_active = True            # 布尔值# Operators - 运算符+, -, *, /, //, %, **       # 加减乘除、整除、取模、幂运算==, !=, >, <, >=, <=        # 比较运算符and, or, not                # 逻辑运算符in, is                      # 成员检测、身份检测# Condition - 条件语句if condition:    passelif condition2:    passelse:    pass# Loops - 循环for i in range(10):         # 循环10次    passfor item in items:          # 遍历列表    passwhile condition:            # while 循环    pass# Functions - 函数定义def greet(name):    return f"Hello, {name}"
// Variables - 变量声明var x int = 10                           // 完整声明var name string = "Go"isActive := true                        // 短变量声明(自动推导类型)// Operators - 运算符+, -, *, /, %                           // 算术运算符==, !=, >, <, >=, <=                   // 比较运算符&&, ||, !                               // 逻辑运算符// Condition - 条件语句if condition {} else if condition2 {} else {}// Loops - Go 只有 for 循环for i := 0; i < 10; i++ {              // 类似 C  for 循环}for _, item := range items {           // range 遍历数组/slice,_ 忽略索引}for key, value := range m {             // range 遍历 map}for condition {                         // while 循环写法}// 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                        // 成员检测、类型检测// Condition - 条件语句if (condition) {} else if (condition2) {} else {}// Loops - 循环for (let i = 0; i < 10; i++) {        // for 循环}for (const item of items) {           // for...of 遍历数组}for (const key in obj) {              // for...in 遍历对象}while (condition) {                    // while 循环}// Functions - 函数定义function greet(name) {    return `Hello, ${name}`;}
// Variables - 变量声明int x = 10;                      // int 类型String name = "Java";             // 字符串类型boolean isActive = true;          // 布尔类型// Operators - 运算符+, -, *, /, %                    // 算术运算符==, !=, >, <, >=, <=            // 比较运算符&&, ||, !                        // 逻辑运算符instanceof                       // 类型检测// Condition - 条件语句if (condition) {} else if (condition2) {} else {}// Loops - 循环for (int i = 0; i < 10; i++) {   // for 循环}for (int item : items) {          // 增强型 for 循环}while (condition) {               // while 循环}do {                              // do-while 循环} while (condition);// 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                -- 逻辑运算符-- Condition - 条件语句if condition thenelseif condition2 thenelseend-- Loops - 循环while condition do          -- while 循环endrepeat                      -- repeat until(类似 do-while)until conditionfor i = 1, 10 do            -- 数值 for 循环endfor i, v in ipairs(arr) do  -- 遍历数组endfor k, v in pairs(dict) do  -- 遍历字典end-- Functions - 函数定义function greet(name)    return "Hello, " .. name   -- .. 为字符串拼接end

Language-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()); // 收集为 List
local 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()                  -- 调用方法

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

https://vluv.space/langs/

Author

GnixAij

Posted

2025-05-19

Updated

2026-01-06

License