16 - 高级特性

想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:https://github.com/tingaicompass/AI-Compass

仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。

16 - 高级特性

学习目标: 掌握lambda, 切片, 解包, 三元表达式等


💻 代码示例

1. lambda表达式

python 复制代码
# 普通函数
def add(x, y):
    return x + y

# lambda(匿名函数)
add = lambda x, y: x + y

# 常用于sorted, map, filter
words = ["banana", "apple", "cherry"]
sorted_words = sorted(words, key=lambda w: len(w))

# 多个参数
points = [(1, 2), (3, 1), (5, 4)]
points.sort(key=lambda p: p[1])  # 按y坐标排序

2. 高级切片

python 复制代码
nums = [0, 1, 2, 3, 4, 5]

# 反转
print(nums[::-1])  # [5, 4, 3, 2, 1, 0]

# 每隔一个取一个
print(nums[::2])   # [0, 2, 4]

# 倒序每隔一个
print(nums[::-2])  # [5, 3, 1]

# 字符串反转
s = "hello"
print(s[::-1])  # olleh

3. 序列解包

python 复制代码
# 多变量赋值
a, b, c = 1, 2, 3

# 交换变量(Python特色!)
a, b = b, a

# *号收集剩余元素
a, *b, c = [1, 2, 3, 4, 5]
print(a)  # 1
print(b)  # [2, 3, 4]
print(c)  # 5

# 函数返回多个值
def get_info():
    return "Alice", 20, "Beijing"

name, age, city = get_info()

# 忽略某些值
x, _, z = (1, 2, 3)  # 用_表示不关心的值

4. 三元表达式(条件表达式)

python 复制代码
# 传统if-else
if x > 0:
    result = "正数"
else:
    result = "非正数"

# 三元表达式(一行搞定)
result = "正数" if x > 0 else "非正数"

# 嵌套三元表达式
sign = "正" if x > 0 else ("零" if x == 0 else "负")

# 在列表推导式中使用
labels = ["偶数" if i % 2 == 0 else "奇数" for i in range(5)]

5. and/or短路运算

python 复制代码
# or:返回第一个真值
x = None
y = x or []  # x是None(假),返回[]
print(y)  # []

# 默认值技巧
def greet(name=None):
    name = name or "Guest"  # name为None时使用"Guest"
    print(f"Hello, {name}!")

# and:全真才返回最后一个值
result = 5 and 10  # 10
result = 0 and 10  # 0 (短路)

# 链式判断
if nums and nums[0] > 0:  # 先检查非空,再访问元素
    print("第一个元素是正数")

6. 列表/字典快速技巧

python 复制代码
# 列表去重(保持顺序)
nums = [1, 2, 2, 3, 1]
unique = list(dict.fromkeys(nums))  # [1, 2, 3]

# 字典合并(Python 3.9+)
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
merged = d1 | d2  # {'a': 1, 'b': 3, 'c': 4}

# 或使用**解包
merged = {**d1, **d2}

# 列表展平
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]

7. enumerate和zip的高级用法

python 复制代码
# enumerate带起始索引
for i, val in enumerate(['a', 'b', 'c'], start=1):
    print(f"第{i}个: {val}")

# zip多个列表
names = ["Alice", "Bob"]
ages = [20, 21]
cities = ["Beijing", "Shanghai"]

for name, age, city in zip(names, ages, cities):
    print(f"{name}, {age}, {city}")

# zip(*list)解压
pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
numbers, letters = zip(*pairs)
print(numbers)  # (1, 2, 3)
print(letters)  # ('a', 'b', 'c')

🎯 在算法题中的应用

python 复制代码
# 切片反转
def reverseString(s):
    return s[::-1]

# 三元表达式
def max(a, b):
    return a if a > b else b

# 序列解包交换
def reverseList(head):
    prev, curr = None, head
    while curr:
        curr.next, prev, curr = prev, curr, curr.next
    return prev

# lambda排序
intervals.sort(key=lambda x: x[0])

# and短路
if root and root.left:
    ...

🎓 小结

lambda: 匿名函数

[::-1]: 反转序列

a, b = b, a: 交换变量

x if cond else y: 三元表达式

x or default: 默认值技巧

*args: 解包

下一步 : 17-递归.md


如果这篇内容对你有帮助,推荐收藏 AI Compass:https://github.com/tingaicompass/AI-Compass

更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。

相关推荐
cpp_25011 天前
P2639 [USACO09OCT] Bessie‘s Weight Problem G
数据结构·算法·动态规划·题解·洛谷·背包dp
郝学胜-神的一滴1 天前
[力扣 227] 双栈妙解表达式计算:从思维逻辑到C++实战,吃透反向波兰式底层原理
java·前端·数据结构·c++·算法
LDG_AGI1 天前
【搜索引擎】Elasticsearch(六):向量搜索深度解析:从参数原理到混合查询实战
人工智能·深度学习·算法·elasticsearch·机器学习·搜索引擎
会编程的土豆1 天前
【数据结构与算法】二叉树深度
算法·深度优先
knight_9___1 天前
RAG面试篇9
java·人工智能·python·算法·agent·rag
贾斯汀玛尔斯1 天前
每天学一个算法--Top-K 查询(Top-K Retrieval)
算法
菜鸟丁小真1 天前
LeetCode hot100 -131.分割回文串
数据结构·算法·leetcode·知识点总结
贾斯汀玛尔斯1 天前
每天学一个算法--PageRank
算法
子琦啊1 天前
【算法复习】滑动窗口(同向区间指针)
算法
啊我不会诶1 天前
【自用复习】牛客每日一题2026.4.18 最大稳定数值
算法·深度优先