初级程序员必备的十大技能之编程语言(三)

简介: 教程来源 https://xgmoi.cn/ 本节详解三大核心数据结构与字符串处理:数组/列表(增删查改、遍历映射)、对象/字典(键值存取、遍历与推导)、Set(去重与集合运算);并涵盖字符串索引切片、大小写、格式化(f-string/模板字符串)及正则匹配/替换,兼顾JS与Python双语言实现。

四、数据结构:组织的艺术

4.1 数组/列表:有序的集合

// JavaScript 数组(动态,可混合类型)
let arr = [1, 2, 3, 4, 5];

// 常用操作
arr.push(6);        // 末尾添加 [1,2,3,4,5,6]
arr.pop();          // 移除末尾 [1,2,3,4,5]
arr.unshift(0);     // 开头添加 [0,1,2,3,4,5]
arr.shift();        // 移除开头 [1,2,3,4,5]
arr[2];             // 索引访问:3
arr.length;         // 长度:5
arr.indexOf(3);     // 查找索引:2
arr.includes(5);    // 是否包含:true

// 切片(不修改原数组)
let slice = arr.slice(1, 4);  // [2,3,4]

// 拼接
let combined = arr.concat([6, 7, 8]);  // [1,2,3,4,5,6,7,8]
# Python 列表
lst = [1, 2, 3, 4, 5]

lst.append(6)           # 末尾添加
lst.pop()               # 移除末尾
lst.insert(0, 0)        # 指定位置插入
lst.remove(3)           # 移除第一个匹配项
lst[2]                  # 索引访问
len(lst)                # 长度
3 in lst                # 成员检查:True

lst.index(4)            # 查找索引
lst.sort()              # 排序(原地)
sorted(lst)             # 返回新排序列表

数组常用算法:

// 遍历
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}

// forEach 高阶函数
arr.forEach(item => console.log(item));

// map:转换每个元素
let doubled = arr.map(x => x * 2);

// filter:筛选元素
let evens = arr.filter(x => x % 2 === 0);

// reduce:归纳计算
let sum = arr.reduce((acc, curr) => acc + curr, 0);

// find:查找第一个匹配
let found = arr.find(x => x > 3);

4.2 对象/字典:键值对的映射

// JavaScript 对象
let user = {
    name: "张三",
    age: 25,
    isActive: true,
    // 方法
    greet() {
        return `你好,我是${this.name}`;
    }
};

// 访问属性
user.name;           // "张三"
user["age"];         // 25(使用变量时有用)

// 添加/修改属性
user.email = "zhangsan@example.com";
user["phone"] = "123456789";

// 删除属性
delete user.phone;

// 遍历对象
for (let key in user) {
    console.log(`${key}: ${user[key]}`);
}

// 获取所有键/值
Object.keys(user);    // ["name", "age", "isActive", ...]
Object.values(user);  // ["张三", 25, true, ...]
Object.entries(user); // [["name","张三"], ["age",25], ...]
# Python 字典
user = {
    "name": "张三",
    "age": 25,
    "is_active": True
}

# 访问(用 get 避免 KeyError)
user["name"]              # "张三"
user.get("email", "无")   # 安全访问,指定默认值

# 添加/修改
user["email"] = "zhangsan@example.com"

# 删除
del user["is_active"]

# 遍历
for key, value in user.items():
    print(f"{key}: {value}")

# 字典推导式
squares = {x: x**2 for x in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}

4.3 Set:不重复的集合

// JavaScript Set
let uniqueNumbers = new Set([1, 2, 3, 3, 4, 4, 5]);
console.log(uniqueNumbers);  // Set(5) {1,2,3,4,5}

uniqueNumbers.add(6);
uniqueNumbers.delete(3);
uniqueNumbers.has(2);  // true
uniqueNumbers.size;    // 5

// 数组去重
let arr = [1, 2, 2, 3, 3, 4];
let unique = [...new Set(arr)];  // [1,2,3,4]
# Python Set
unique_numbers = {1, 2, 3, 3, 4, 4, 5}
print(unique_numbers)  # {1,2,3,4,5}

unique_numbers.add(6)
unique_numbers.remove(3)
2 in unique_numbers  # True
len(unique_numbers)  # 5

# 集合运算
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

set1 | set2  # 并集 {1,2,3,4,5,6}
set1 & set2  # 交集 {3,4}
set1 - set2  # 差集 {1,2}
set1 ^ set2  # 对称差 {1,2,5,6}

五、字符串处理:文本的艺术

https://amwtm.cn/
5.1 字符串基础操作

# Python 字符串
text = "Hello, World!"

# 长度
len(text)  # 13

# 索引(0开始,负数表示从末尾)
text[0]    # 'H'
text[-1]   # '!'

# 切片 [start:end:step]
text[0:5]     # 'Hello'
text[7:]      # 'World!'
text[::2]     # 'Hlo ol!'(步长2)
text[::-1]    # '!dlroW ,olleH'(反转)

# 大小写转换
text.upper()      # 'HELLO, WORLD!'
text.lower()      # 'hello, world!'
text.capitalize() # 'Hello, world!'
text.title()      # 'Hello, World!'

# 查找替换
text.find("World")    # 7(返回索引,找不到返回-1)
text.replace("World", "Python")  # 'Hello, Python!'

# 分割连接
words = text.split(", ")  # ['Hello', 'World!']
" ".join(words)           # 'Hello World!'

# 去除空白
"  hello  ".strip()   # 'hello'
// JavaScript 字符串
let text = "Hello, World!";

text.length;        // 13
text[0];            // 'H'
text.charAt(0);     // 'H'
text.indexOf("World");  // 7
text.includes("Hello"); // true

text.slice(0, 5);   // 'Hello'(支持负数)
text.substring(0, 5); // 不支持负数
text.substr(7, 5);  // 'World'(已废弃)

text.toUpperCase(); // 'HELLO, WORLD!'
text.toLowerCase(); // 'hello, world!'

text.replace("World", "JavaScript");  // 'Hello, JavaScript!'
text.split(", ");   // ['Hello', 'World!']
text.trim();        // 去除两端空白

// 模板字符串(ES6)
let name = "张三";
let age = 25;
let message = `我叫${name},今年${age}岁`;  // 支持换行和表达式

5.2 字符串格式化

# Python 三种格式化方式

# 1. % 格式化(旧式)
name = "张三"
score = 95.5
print("姓名:%s,分数:%.1f" % (name, score))

# 2. str.format() 方法
print("姓名:{},分数:{}".format(name, score))
print("姓名:{n},分数:{s}".format(n=name, s=score))

# 3. f-strings(Python 3.6+,推荐)
print(f"姓名:{name},分数:{score:.1f}")
print(f"计算结果:{10 + 20}")
print(f"三倍:{score * 3:.2f}")
// JavaScript 字符串格式化

// 1. 模板字符串(推荐)
let name = "张三";
let score = 95.5;
console.log(`姓名:${name},分数:${score}`);

// 2. 拼接
console.log("姓名:" + name + ",分数:" + score);

5.3 正则表达式基础

// JavaScript 正则表达式
let email = "user@example.com";

// 测试是否匹配
let emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
console.log(emailPattern.test(email));  // true

// 提取匹配内容
let text = "我的电话是 138-1234-5678";
let phonePattern = /(\d{3})-(\d{4})-(\d{4})/;
let match = text.match(phonePattern);
console.log(match[1]);  // 138
console.log(match[2]);  // 1234
console.log(match[3]);  // 5678

// 替换
let phone = "13812345678";
let formatted = phone.replace(/(\d{3})(\d{4})(\d{4})/, "$1-$2-$3");
console.log(formatted);  // 138-1234-5678
# Python 正则表达式
import re

email = "user@example.com"
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
print(bool(re.match(pattern, email)))  # True

# 查找所有匹配
text = "我的电话是 138-1234-5678,备用 139-8765-4321"
phone_pattern = r'(\d{3})-(\d{4})-(\d{4})'
matches = re.findall(phone_pattern, text)
print(matches)  # [('138','1234','5678'), ('139','8765','4321')]

# 替换
phone = "13812345678"
formatted = re.sub(r'(\d{3})(\d{4})(\d{4})', r'\1-\2-\3', phone)
print(formatted)  # 138-1234-5678
相关文章
|
13天前
|
人工智能 JSON 供应链
畅用7个月无影 JVS Claw |手把手教你把JVS改造成「科研与产业地理情报可视化大师」
LucianaiB分享零成本畅用JVS Claw教程(学生认证享7个月使用权),并开源GeoMind项目——将JVS改造为科研与产业地理情报可视化AI助手,支持飞书文档解析、地理编码与腾讯地图可视化,助力产业关系图谱构建。
23495 11
畅用7个月无影 JVS Claw |手把手教你把JVS改造成「科研与产业地理情报可视化大师」
|
17天前
|
人工智能 缓存 BI
Claude Code + DeepSeek V4-Pro 真实评测:除了贵,没别的毛病
JeecgBoot AI专题研究 把 Claude Code 接入 DeepSeek V4Pro,跑完 Skills —— OA 审批、大屏、报表、部署 5 大实战场景后的真实体验 ![](https://oscimg.oschina.net/oscnet/up608d34aeb6bafc47f
5475 20
Claude Code + DeepSeek V4-Pro 真实评测:除了贵,没别的毛病
|
18天前
|
人工智能 JSON BI
DeepSeek V4 来了!超越 Claude Sonnet 4.5,赶紧对接 Claude Code 体验一把
JeecgBoot AI专题研究 把 Claude Code 接入 DeepSeek V4Pro 的真实体验与避坑记录 本文记录我将 Claude Code 对接 DeepSeek 最新模型(V4Pro)后的真实体验,测试了 Skills 自动化查询和积木报表 AI 建表两个场景——有惊喜,也踩
6539 16
|
7天前
|
人工智能 缓存 Shell
Claude Code 全攻略:命令大全 + 实战工作流(完整版)
Claude Code 是一款运行在终端环境下的 AI 编码助手,能够直接在项目目录中理解代码结构、编辑文件、执行命令、执行开发计划,并支持持久化记忆、上下文压缩、后台任务、多模型切换等专业能力。对于日常开发、项目维护、快速重构、代码审查等场景,它可以大幅减少手动操作、提升编码效率。本文从常用命令、界面模式、核心指令、记忆机制、图片处理、进阶工作流等维度完整说明,帮助开发者快速上手并稳定使用。
1664 3
|
6天前
|
前端开发 API 内存技术
对比claude code等编程cli工具与deepseek v4的适配情况
DeepSeek V4发布后,多家编程工具因未适配其强制要求的`reasoning_content`字段而报错。本文对比Claude Code、GitHub Copilot、Langcli、OpenCode及DeepSeek-TUI等主流工具的兼容性:Claude Code需按官方方式配置;Langcli表现最佳,开箱即用且无报错;Copilot与OpenCode暂未修复问题;DeepSeek-TUI尚处早期阶段。
1130 3
对比claude code等编程cli工具与deepseek v4的适配情况
|
2天前
|
人工智能 BI 持续交付
Claude Code 深度适配 DeepSeek V4-Pro 实测:全场景通关与真实体验报告
在 AI 编程工具日趋主流的今天,Claude Code 凭借强大的任务执行、工具调用与工程化能力,成为开发者与自动化运维的核心效率工具。但随着原生模型账号稳定性问题频发,寻找一套兼容、稳定、能力在线的替代方案变得尤为重要。DeepSeek V4-Pro 作为新一代高性能大模型,提供了完整兼容 Claude 协议的 API 接口,只需简单配置即可无缝驱动 Claude Code,且在任务执行、工具调用、复杂流程处理上表现极为稳定。
838 0
|
1月前
|
人工智能 自然语言处理 安全
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)
本文介绍了Claude Code终端AI助手的使用指南,主要内容包括:1)常用命令如版本查看、项目启动和更新;2)三种工作模式切换及界面说明;3)核心功能指令速查表,包含初始化、压缩对话、清除历史等操作;4)详细解析了/init、/help、/clear、/compact、/memory等关键命令的使用场景和语法。文章通过丰富的界面截图和场景示例,帮助开发者快速掌握如何通过命令行和交互界面高效使用Claude Code进行项目开发,特别强调了CLAUDE.md文件作为项目知识库的核心作用。
27256 65
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)