🔧 Python常用内置函数详解:从入门到精通的完全指南

Python内置函数是编程中最常用、最强大的工具,无需导入任何模块即可使用。本文将详细解析Python最常用的内置函数,帮助你从入门到精通。

📌 数据类型转换函数

1. int(), float(), str(), bool()

基础类型转换是编程中最常用的操作:

# 字符串转整数
num = int("42")           # 42
num = int("101", 2)       # 5 (二进制转十进制)

# 转浮点数
price = float("19.99")    # 19.99

# 转字符串
text = str(123)           # "123"

# 转布尔值
flag = bool(1)            # True
flag = bool("")           # False (空字符串为False)
flag = bool([])           # False (空列表为False)

📊 序列操作函数

2. len() - 获取长度

len("Hello")              # 5
len([1, 2, 3])            # 3
len({"a": 1, "b": 2})     # 2

3. range() - 生成数字序列

# 基础用法
for i in range(5):        # 0, 1, 2, 3, 4
    print(i)

# 指定起始和步长
for i in range(2, 10, 2): # 2, 4, 6, 8
    print(i)

# 转列表
list(range(5))            # [0, 1, 2, 3, 4]

4. enumerate() - 带索引的迭代

fruits = ["apple", "banana", "cherry"]

# 获取索引和值
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# 指定起始索引
for index, fruit in enumerate(fruits, start=1):
    print(f"{index}. {fruit}")

5. zip() - 并行迭代多个序列

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

# 打包多个列表
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

# 解压
data = [("Alice", 25), ("Bob", 30)]
names, ages = zip(*data)

🔄 函数式编程函数

6. map() - 映射函数到序列

# 平方每个元素
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25]

7. filter() - 过滤序列

# 过滤偶数
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6, 8, 10]

8. sorted() - 排序

# 基础排序
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted(numbers)                    # [1, 1, 2, 3, 4, 5, 9]

# 降序排序
sorted(numbers, reverse=True)      # [9, 5, 4, 3, 2, 1, 1]

# 自定义排序键
words = ["banana", "pie", "Washington"]
sorted(words, key=len)             # ["pie", "banana", "Washington"]

📋 其他常用函数

9. sum(), min(), max()

numbers = [1, 2, 3, 4, 5]

sum(numbers)              # 15
min(numbers)              # 1
max(numbers)              # 5

# 自定义key
words = ["apple", "banana", "cherry"]
max(words, key=len)       # "banana" (最长单词)

10. any() 和 all()

# any: 任一元素为True则返回True
any([False, True, False])    # True

# all: 所有元素为True才返回True
all([True, True, True])      # True

# 实际应用
scores = [85, 90, 78, 92]
all(score >= 60 for score in scores)  # 是否全部及格
any(score >= 95 for score in scores)  # 是否有优秀

🎯 最佳实践总结

场景推荐函数
类型转换 int(), str(), float()
获取长度 len()
遍历带索引 enumerate()
多序列并行 zip()
数据转换 map()
数据过滤 filter()
排序 sorted()
类型检查 isinstance()
所有/任一判断 all(), any()

掌握这些内置函数,能让你的Python代码更简洁、更高效!💪

本文为AI辅助生成的Python教程,内容经过整理确保准确性。

posted @ 2026-03-23 17:43  码小小小仙  阅读(20)  评论(0)    收藏  举报