想系统提升编程能力、查看更完整的学习路线,欢迎访问 AI Compass:https://github.com/tingaicompass/AI-Compass
仓库持续更新刷题题解、Python 基础和 AI 实战内容,适合想高效进阶的你。
12 - 内置函数:Python的瑞士军刀
学习目标: 掌握算法题中最常用的内置函数
📖 知识点讲解
Python内置了很多强大的函数,不需要import就能直接使用。这些函数能让代码更简洁、更高效。
重要性: 算法题中**90%**都会用到这些内置函数!
💻 代码示例
1. len() - 获取长度
python
# 列表长度
nums = [1, 2, 3, 4, 5]
print(len(nums)) # 5
# 字符串长度
s = "hello"
print(len(s)) # 5
# 字典长度(键值对数量)
d = {"a": 1, "b": 2}
print(len(d)) # 2
# 集合长度
s = {1, 2, 3}
print(len(s)) # 3
# ⚠️ 常见错误
x = 123
# print(len(x)) # ❌ TypeError: 数字没有长度
在算法题中:
python
# 遍历数组
for i in range(len(nums)): # ← len获取数组长度
print(nums[i])
2. range() - 生成数字序列
python
# range(stop): 从0到stop-1
for i in range(5):
print(i, end=" ") # 0 1 2 3 4
print()
# range(start, stop): 从start到stop-1
for i in range(2, 5):
print(i, end=" ") # 2 3 4
print()
# range(start, stop, step): 带步长
for i in range(0, 10, 2):
print(i, end=" ") # 0 2 4 6 8
print()
# 倒序
for i in range(5, 0, -1):
print(i, end=" ") # 5 4 3 2 1
print()
# 转成列表
nums = list(range(5))
print(nums) # [0, 1, 2, 3, 4]
3. enumerate() - 同时获取索引和值
python
fruits = ["apple", "banana", "cherry"]
# 不用enumerate(繁琐)
for i in range(len(fruits)):
print(f"索引{i}: {fruits[i]}")
# 使用enumerate(优雅!)
for i, fruit in enumerate(fruits):
print(f"索引{i}: {fruit}")
# 索引0: apple
# 索引1: banana
# 索引2: cherry
# 指定起始索引
for i, fruit in enumerate(fruits, start=1):
print(f"第{i}个: {fruit}")
# 第1个: apple
# 第2个: banana
# 第3个: cherry
在算法题中 (第1课:两数之和):
python
def twoSum(nums, target):
seen = {}
for i, num in enumerate(nums): # ← 同时获取索引和值
if target - num in seen:
return [seen[target - num], i]
seen[num] = i
4. zip() - 并行遍历多个序列
python
names = ["Alice", "Bob", "Charlie"]
scores = [90, 85, 92]
# 并行遍历
for name, score in zip(names, scores):
print(f"{name}: {score}")
# Alice: 90
# Bob: 85
# Charlie: 92
# 转成字典
student_scores = dict(zip(names, scores))
print(student_scores) # {'Alice': 90, 'Bob': 85, 'Charlie': 92}
# 不同长度(以最短为准)
a = [1, 2, 3, 4]
b = ['a', 'b']
print(list(zip(a, b))) # [(1, 'a'), (2, 'b')]
5. sorted() - 排序(返回新列表)
python
nums = [3, 1, 4, 1, 5, 9, 2, 6]
# 升序排序
sorted_nums = sorted(nums)
print(sorted_nums) # [1, 1, 2, 3, 4, 5, 6, 9]
print(nums) # [3, 1, 4, 1, 5, 9, 2, 6] (原列表不变)
# 降序排序
sorted_nums = sorted(nums, reverse=True)
print(sorted_nums) # [9, 6, 5, 4, 3, 2, 1, 1]
# 字符串排序
words = ["banana", "apple", "cherry"]
print(sorted(words)) # ['apple', 'banana', 'cherry']
# 按长度排序(使用key参数)
print(sorted(words, key=len)) # ['apple', 'banana', 'cherry']
# 按自定义规则排序
points = [(1, 2), (3, 1), (2, 3)]
print(sorted(points, key=lambda p: p[1])) # 按第二个元素排序
# [(3, 1), (1, 2), (2, 3)]
sorted() vs list.sort():
python
nums = [3, 1, 4]
# sorted(): 返回新列表,原列表不变
new_nums = sorted(nums)
print(nums) # [3, 1, 4]
print(new_nums) # [1, 3, 4]
# list.sort(): 原地排序,返回None
nums.sort()
print(nums) # [1, 3, 4]
在算法题中 (第2课:字母异位词分组):
python
def groupAnagrams(strs):
groups = {}
for word in strs:
key = "".join(sorted(word)) # ← sorted排序字符
groups[key] = groups.get(key, []) + [word]
return list(groups.values())
6. max() / min() - 最大值/最小值
python
nums = [3, 1, 4, 1, 5, 9]
print(max(nums)) # 9
print(min(nums)) # 1
# 多个参数
print(max(1, 5, 3, 8, 2)) # 8
# 字符串比较(按字典序)
words = ["apple", "banana", "cherry"]
print(max(words)) # cherry
print(min(words)) # apple
# 使用key参数
words = ["a", "bbb", "cc"]
print(max(words, key=len)) # bbb (最长的)
print(min(words, key=len)) # a (最短的)
# 空序列会报错
# print(max([])) # ❌ ValueError
# 解决方法:提供default
print(max([], default=0)) # 0
7. sum() - 求和
python
nums = [1, 2, 3, 4, 5]
print(sum(nums)) # 15
# 指定起始值
print(sum(nums, 10)) # 25 (10 + 1 + 2 + 3 + 4 + 5)
# 空列表
print(sum([])) # 0
# ⚠️ sum只能用于数字
# print(sum(["a", "b"])) # ❌ TypeError
8. all() / any() - 逻辑判断
python
# all(): 所有元素都为True才返回True
print(all([True, True, True])) # True
print(all([True, False, True])) # False
print(all([])) # True (空列表返回True)
# any(): 至少一个元素为True就返回True
print(any([False, False, True])) # True
print(any([False, False, False])) # False
print(any([])) # False (空列表返回False)
# 实际应用
nums = [2, 4, 6, 8]
print(all(n % 2 == 0 for n in nums)) # True (所有数都是偶数)
nums = [1, 3, 5, 7]
print(any(n % 2 == 0 for n in nums)) # False (没有偶数)
9. reversed() - 反转序列
python
nums = [1, 2, 3, 4, 5]
# reversed()返回迭代器,需要转成列表
reversed_nums = list(reversed(nums))
print(reversed_nums) # [5, 4, 3, 2, 1]
print(nums) # [1, 2, 3, 4, 5] (原列表不变)
# 反转字符串
s = "hello"
print("".join(reversed(s))) # olleh
# 或者用切片(更简洁)
print(nums[::-1]) # [5, 4, 3, 2, 1]
10. map() / filter() - 函数式编程
python
nums = [1, 2, 3, 4, 5]
# map(): 对每个元素应用函数
squared = list(map(lambda x: x**2, nums))
print(squared) # [1, 4, 9, 16, 25]
# 等价于列表推导式(更Pythonic)
squared = [x**2 for x in nums]
print(squared) # [1, 4, 9, 16, 25]
# filter(): 过滤元素
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
# 等价于列表推导式(更Pythonic)
evens = [x for x in nums if x % 2 == 0]
print(evens) # [2, 4]
建议: 优先使用列表推导式,更易读!
11. int() / str() / list() / set() / tuple() - 类型转换
python
# 字符串转数字
x = int("123")
print(x) # 123
# 数字转字符串
s = str(456)
print(s) # "456"
# 字符串转列表
s = "hello"
chars = list(s)
print(chars) # ['h', 'e', 'l', 'l', 'o']
# 列表转集合(去重)
nums = [1, 2, 2, 3, 3, 3]
unique = set(nums)
print(unique) # {1, 2, 3}
# 集合转列表
unique_list = list(unique)
print(unique_list) # [1, 2, 3]
12. abs() - 绝对值
python
print(abs(-5)) # 5
print(abs(3.14)) # 3.14
print(abs(-0)) # 0
# 在算法题中
distance = abs(x1 - x2) # 两点距离
13. pow() - 幂运算
python
print(pow(2, 3)) # 8 (2的3次方)
print(2 ** 3) # 8 (等价写法,更常用)
# 三个参数:幂取模
print(pow(2, 10, 1000)) # 24 (2^10 % 1000)
🎯 内置函数速查表
| 函数 | 功能 | 常用度 | 示例 |
|---|---|---|---|
len() |
获取长度 | ⭐⭐⭐⭐⭐ | len([1,2,3]) → 3 |
range() |
生成序列 | ⭐⭐⭐⭐⭐ | range(5) → 0,1,2,3,4 |
enumerate() |
索引+值 | ⭐⭐⭐⭐⭐ | enumerate([a,b]) → (0,a),(1,b) |
sorted() |
排序 | ⭐⭐⭐⭐⭐ | sorted([3,1,2]) → [1,2,3] |
max()/min() |
最值 | ⭐⭐⭐⭐ | max([1,5,3]) → 5 |
sum() |
求和 | ⭐⭐⭐⭐ | sum([1,2,3]) → 6 |
zip() |
并行遍历 | ⭐⭐⭐ | zip([1,2],[a,b]) |
all()/any() |
逻辑判断 | ⭐⭐⭐ | all([True,False]) → False |
reversed() |
反转 | ⭐⭐⭐ | reversed([1,2,3]) |
abs() |
绝对值 | ⭐⭐⭐ | abs(-5) → 5 |
🏋️ 快速练习
练习1:找出列表中所有偶数的平方
python
nums = [1, 2, 3, 4, 5, 6]
# 期望输出: [4, 16, 36]
点击查看答案
python
nums = [1, 2, 3, 4, 5, 6]
# 方法1:列表推导式(推荐)
result = [x**2 for x in nums if x % 2 == 0]
print(result) # [4, 16, 36]
# 方法2:filter + map
result = list(map(lambda x: x**2, filter(lambda x: x % 2 == 0, nums)))
print(result)
练习2:合并两个列表为字典
python
keys = ["name", "age", "city"]
values = ["Alice", 25, "Beijing"]
# 期望输出: {"name": "Alice", "age": 25, "city": "Beijing"}
点击查看答案
python
keys = ["name", "age", "city"]
values = ["Alice", 25, "Beijing"]
# 使用zip和dict
result = dict(zip(keys, values))
print(result) # {"name": "Alice", "age": 25, "city": "Beijing"}
🎓 小结
掌握这些内置函数,代码会更简洁优雅!
必须记住的:
len(x)- 长度for i in range(n)- 循环n次for i, val in enumerate(list)- 获取索引和值sorted(list)- 排序max(list),min(list),sum(list)- 最大值、最小值、求和
下一步 : 13-collections模块.md
熟练使用内置函数是Python高手的标志! 🚀
如果这篇内容对你有帮助,推荐收藏 AI Compass:https://github.com/tingaicompass/AI-Compass
更多系统化题解、编程基础和 AI 学习资料都在这里,后续复习和拓展会更省时间。