16 - 高级特性

0 阅读3分钟

想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:github.com/tingaicompa… 仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。

16 - 高级特性

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


💻 代码示例

1. lambda表达式

# 普通函数
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. 高级切片

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. 序列解包

# 多变量赋值
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. 三元表达式(条件表达式)

# 传统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短路运算

# 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. 列表/字典快速技巧

# 列表去重(保持顺序)
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的高级用法

# 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')

🎯 在算法题中的应用

# 切片反转
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:github.com/tingaicompa… 更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。