Logo
Published on

3.2.内置函数

Authors
  • avatar
    Name
    xiaobai
    Twitter

1.概述

Python提供了丰富的内置函数,这些函数无需导入任何模块即可直接使用。内置函数涵盖了数学运算、类型转换、序列操作、输入输出等各个方面,是Python编程的基础工具。

2.核心概念

2.1.内置函数的优势

优势描述示例
无需导入直接使用,无需import语句print(), len(), max()
高效实现底层C实现,性能优异sum()比手动循环快
标准化统一的接口和行为所有Python版本都支持
功能丰富覆盖常用操作场景数学、字符串、集合等

2.2.内置函数分类

分类主要函数用途
数学运算abs(), round(), pow(), max(), min()数值计算
类型转换int(), float(), str(), bool(), list()数据类型转换
序列操作len(), sum(), sorted(), reversed()序列处理
输入输出print(), input()用户交互
迭代器range(), enumerate(), zip(), map()迭代处理
对象操作type(), isinstance(), hasattr()对象检查

3.数学运算函数

3.1.基本数学函数

# abs() - 返回绝对值
print(abs(-5))      # 5
print(abs(3.14))    # 3.14

# round() - 四舍五入
print(round(3.14159, 2))  # 3.14
print(round(3.5))         # 4

# pow() - 幂运算
print(pow(2, 3))     # 8
print(pow(2, 3, 5))  # 3 (2^3 % 5)

# divmod() - 返回商和余数
quotient, remainder = divmod(10, 3)
print(quotient, remainder)  # 3 1

3.2.最值函数

# max() / min() - 最大值/最小值
numbers = [1, 5, 2, 8, 3]
print(max(numbers))  # 8
print(min(numbers))  # 1

# 支持多个参数
print(max(1, 5, 3))  # 5
print(min(1, 5, 3))  # 1

# 支持字符串比较
print(max("abcXYZ"))  # 'c'(按Unicode顺序)
print(min("abcXYZ"))  # 'X'

4.类型转换函数

4.1.基本类型转换

# int(), float(), str(), bool()
print(int("123"))        # 123
print(float("3.14"))     # 3.14
print(str(456))          # "456"
print(bool(0))           # False
print(bool(1))           # True
print(bool(""))          # False
print(bool("hello"))     # True

4.2.集合类型转换

# list(), tuple(), set(), dict()
print(list("hello"))     # ['h', 'e', 'l', 'l', 'o']
print(tuple([1, 2, 3]))  # (1, 2, 3)
print(set([1, 2, 2, 3])) # {1, 2, 3} (自动去重)

# dict() 转换
pairs = [('a', 1), ('b', 2)]
print(dict(pairs))       # {'a': 1, 'b': 2}

4.3.特殊转换函数

# chr() / ord() - 字符与ASCII码转换
print(chr(65))           # 'A'
print(ord('A'))          # 65

# bin(), oct(), hex() - 进制转换
print(bin(10))           # '0b1010'
print(oct(10))           # '0o12'
print(hex(255))          # '0xff'

5.序列操作函数

5.1.长度和统计

# len() - 获取序列长度
print(len("python"))        # 6
print(len([10, 20, 30]))    # 3
print(len({'a': 1, 'b': 2})) # 2

# sum() - 求和
scores = [80, 90, 75]
print(sum(scores))          # 245
print(sum([1, 2, 3], 10))   # 16 (可指定初始值)

5.2.排序和反转

# sorted() - 返回排序后的新列表
letters = ['b', 'd', 'a', 'c']
print(sorted(letters))      # ['a', 'b', 'c', 'd']
print(sorted(letters, reverse=True))  # ['d', 'c', 'b', 'a']

# reversed() - 生成反向迭代器
nums = [1, 2, 3]
for n in reversed(nums):
    print(n, end=" ")       # 输出: 3 2 1
print(list(reversed(nums))) # [3, 2, 1]

5.3.枚举和打包

# enumerate() - 枚举索引和元素
foods = ["apple", "banana", "pear"]
for idx, food in enumerate(foods):
    print(idx, food)        # 0 apple, 1 banana, 2 pear

# zip() - 并行打包多个序列
names = ['Tom', 'Jerry']
ages = [8, 9]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

5.4.逻辑判断

# any() / all() - 逻辑判断
flags = [True, False, True]
print(any(flags))           # True,只要有一个为True返回True
print(all(flags))           # False,全部为True才返回True

# 实际应用
scores = [80, 70, 65, 90]
print(all(s > 60 for s in scores))  # 检查是否都及格 -> True
print(any(s < 60 for s in scores))  # 是否有挂科 -> False

6.输入输出函数

6.1.input() 函数

input() 从标准输入(通常为键盘)获取用户输入,返回字符串类型。

# 基本用法
name = input("请输入你的名字: ")
print(f"你好, {name}!")

# 类型转换
age = int(input("请输入你的年龄: "))
print(f"你明年就 {age + 1} 岁了!")

注意事项

  • input() 返回的始终是字符串
  • 需要数字时要用 int()float() 转换
  • 可以显示提示信息

6.2.print() 函数

print() 向标准输出(控制台)打印内容,支持多种格式参数。

# 基本语法:print(value1, value2, ..., sep="分隔符", end="结束符")
print("Python", "很", "好用", sep="--")   # 输出: Python--很--好用
print("Hello", end="!")                  # 输出: Hello!

# 格式化输出
x = 5
print(f"x 的平方是 {x**2}")  # 输出: x 的平方是 25

# 输出变量和表达式
numbers = [1, 2, 3]
print("列表:", numbers)  # 输出: 列表: [1, 2, 3]

参数说明

  • sep:指定不同对象之间的分隔字符串(默认是空格)
  • end:指定输出行的结尾字符串(默认是换行符 \n

7.迭代器和生成器相关

7.1.range() 函数

range() 生成连续整数序列,返回可迭代对象(不是列表)。

# 基本用法
for i in range(5):
    print(i, end=" ")  # 输出: 0 1 2 3 4

for i in range(3, 8):
    print(i, end=" ")  # 输出: 3 4 5 6 7

for i in range(0, 10, 2):
    print(i, end=" ")  # 输出: 0 2 4 6 8

for i in range(5, 0, -2):
    print(i, end=" ")  # 输出: 5 3 1

语法

  • range(stop):从 0 开始,到 stop(不包含 stop)
  • range(start, stop):从 start 开始,到 stop(不包含 stop)
  • range(start, stop, step):从 start 开始,步长为 step

注意事项

  • Python 3 中,range() 返回的不是列表
  • 需要用 list(range(...)) 转换为列表
  • stop 不包含在结果序列内

7.2.enumerate() 函数

enumerate(iterable, start=0) 返回枚举对象,包含索引和值。

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
    print(i, fruit)
# 输出:
# 0 apple
# 1 banana
# 2 cherry

# 自定义起始索引
for i, fruit in enumerate(fruits, start=1):
    print(i, fruit)
# 输出:
# 1 apple
# 2 banana
# 3 cherry

7.3.zip() 函数

zip(*iterables) 并行遍历多个可迭代对象,将相同位置的元素打包成元组。

names = ['Tom', 'Jerry', 'Spike']
scores = [95, 98, 88]
for name, score in zip(names, scores):
    print(name, score)
# 输出:
# Tom 95
# Jerry 98
# Spike 88

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

注意事项

  • 如果传入的可迭代对象长度不同,则以最短的为准
  • 多余的元素被忽略

7.4.map() 和 filter() 函数

7.4.1.map() 函数

map(func, iterable) 对可迭代对象的每个元素应用函数,返回新的迭代器。

# 将字符串转换为大写
words = ["hello", "world", "python"]
upper_words = list(map(str.upper, words))
print(upper_words)   # ['HELLO', 'WORLD', 'PYTHON']

# 使用lambda函数
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # [1, 4, 9, 16]

7.4.2.filter() 函数

filter(func, iterable) 筛选出使函数返回 True 的元素,返回新的迭代器。

# 过滤出长度大于5的单词
words = ["apple", "banana", "cat", "elephant"]
long_words = list(filter(lambda w: len(w) > 5, words))
print(long_words)   # ['banana', 'elephant']

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

注意事项

  • mapfilter 都返回迭代器
  • 需要用 list()for 循环取出结果
  • 常与 lambda 表达式配合使用

7.5.reversed() 和 sorted() 函数

7.5.1.reversed() 函数

reversed(iterable) 返回反向迭代器,不改变原对象。

# 反向遍历
for c in reversed("abcde"):
    print(c, end=" ")  # e d c b a

# 转换为列表
nums = [1, 2, 3]
reversed_nums = list(reversed(nums))
print(reversed_nums)  # [3, 2, 1]

7.5.2.sorted() 函数

sorted(iterable, key=None, reverse=False) 返回排序后的新列表,不修改原数据。

# 基本排序
numbers = [3, 1, 4, 1, 5]
print(sorted(numbers))  # [1, 1, 3, 4, 5]

# 自定义排序
nums = [-3, 2, 1, -5]
print(sorted(nums, key=abs))  # [1, 2, -3, -5] (按绝对值排序)
print(sorted(nums, key=abs, reverse=True))  # [-5, -3, 2, 1]

# 字符串排序
words = ['apple', 'banana', 'cherry', 'date']
print(sorted(words, key=len))  # ['date', 'apple', 'banana', 'cherry'] (按长度排序)

对比

函数功能是否原地改变对象
reversed反向迭代器
sorted排序复制新列表
list.sort原地排序

8.对象操作和属性函数

8.1.类型检查函数

# type() - 获取对象类型
print(type("hello"))        # <class 'str'>
print(type([1, 2, 3]))      # <class 'list'>

# isinstance() - 检查对象类型
print(isinstance(5, int))    # True
print(isinstance(5, float))  # False
print(isinstance(5, (int, float)))  # True (支持类型元组)

8.2.属性操作函数

class Student:
    def __init__(self, name):
        self.name = name

s = Student("Tom")

# hasattr() - 检查对象是否有指定属性
print(hasattr(s, 'name'))      # True
print(hasattr(s, 'age'))       # False

# getattr() - 获取对象属性值
print(getattr(s, 'name'))      # Tom
print(getattr(s, 'age', 'N/A'))# N/A (提供默认值)

# setattr() - 设置对象属性
setattr(s, 'age', 20)
print(s.age)                   # 20

# delattr() - 删除对象属性
delattr(s, 'age')
print(hasattr(s, 'age'))       # False

8.3.其他对象函数

# callable() - 检查对象是否可调用
print(callable(print))         # True
print(callable(len))           # True
print(callable(10))            # False

# dir() - 返回对象的所有属性列表
print(dir(s))                  # 显示s的所有属性和方法名

# vars() - 返回对象的属性字典
print(vars(s))                 # {'name': 'Tom'}

# id() - 返回对象的唯一标识
print(id(s))                   # 内存地址

# bool() - 转换为布尔值
print(bool([1, 2, 3]))         # True
print(bool([]))                # False
print(bool(0))                 # False
print(bool("hello"))           # True

9.高级函数

9.1.reduce() 函数

reduce(func, iterable[, initial]) 对可迭代对象执行累积计算,需要从 functools 导入。

from functools import reduce

numbers = [1, 2, 3, 4]

# 连乘:1*2*3*4
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 24

# 连加:1+2+3+4
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 10

# 带初始值
result = reduce(lambda x, y: x + y, numbers, 10)
print(result)  # 20 (10 + 1 + 2 + 3 + 4)

9.2.函数式编程组合

# 链式使用内置函数
numbers = [5, 2, 8, 1, 9, 3]
result = sorted(filter(lambda x: x > 3, numbers))
print(result)  # [5, 8, 9]

# 使用生成器表达式
total = sum(x * 2 for x in numbers if x % 2 == 0)
print(total)  # 20

10.实用技巧和最佳实践

10.1.1. 函数式编程组合

# 链式使用内置函数
numbers = [5, 2, 8, 1, 9, 3]
result = sorted(filter(lambda x: x > 3, numbers))
print(result)  # [5, 8, 9]

10.2.2. 生成器表达式与内置函数

# 更高效的内存使用
numbers = [1, 2, 3, 4, 5]
# 使用生成器表达式而不是列表推导式
total = sum(x * 2 for x in numbers if x % 2 == 0)
print(total)  # 12

10.3.3. 自定义排序

# 使用key参数进行复杂排序
words = ['apple', 'banana', 'cherry', 'date']
# 按字符串长度排序
print(sorted(words, key=len))  # ['date', 'apple', 'banana', 'cherry']

# 按字符串长度降序排序
print(sorted(words, key=len, reverse=True))  # ['banana', 'cherry', 'apple', 'date']

10.4.4. 错误处理

# 安全的类型转换
def safe_int(value, default=0):
    try:
        return int(value)
    except (ValueError, TypeError):
        return default

print(safe_int("123"))    # 123
print(safe_int("abc"))    # 0
print(safe_int(None))     # 0

10.5.5. 性能优化

# 使用内置函数而不是手动循环
numbers = [1, 2, 3, 4, 5]

# 推荐:使用内置函数
total = sum(numbers)
maximum = max(numbers)

# 不推荐:手动循环
total = 0
for num in numbers:
    total += num

maximum = numbers[0]
for num in numbers:
    if num > maximum:
        maximum = num

11.综合示例

11.1.学生成绩管理系统

def analyze_student_scores(scores):
    """分析学生成绩"""
    if not scores:
        return None
    
    # 使用内置函数进行统计分析
    analysis = {
        'count': len(scores),
        'total': sum(scores),
        'average': sum(scores) / len(scores),
        'max_score': max(scores),
        'min_score': min(scores),
        'sorted_scores': sorted(scores, reverse=True),
        'passed_count': sum(1 for score in scores if score >= 60),
        'failed_count': sum(1 for score in scores if score < 60)
    }
    
    return analysis

# 使用示例
scores = [85, 92, 78, 96, 88, 73, 91, 67, 89, 94]
result = analyze_student_scores(scores)
print(f"学生人数: {result['count']}")
print(f"总分: {result['total']}")
print(f"平均分: {result['average']:.2f}")
print(f"最高分: {result['max_score']}")
print(f"最低分: {result['min_score']}")
print(f"及格人数: {result['passed_count']}")
print(f"不及格人数: {result['failed_count']}")

11.2.数据处理管道

def process_data(data):
    """数据处理管道"""
    # 1. 过滤有效数据
    valid_data = list(filter(lambda x: x is not None and x > 0, data))
    
    # 2. 数据转换
    processed_data = list(map(lambda x: x * 2, valid_data))
    
    # 3. 排序
    sorted_data = sorted(processed_data)
    
    # 4. 统计
    stats = {
        'count': len(sorted_data),
        'sum': sum(sorted_data),
        'max': max(sorted_data) if sorted_data else 0,
        'min': min(sorted_data) if sorted_data else 0
    }
    
    return sorted_data, stats

# 使用示例
raw_data = [1, 2, None, 3, -1, 4, 0, 5]
processed, stats = process_data(raw_data)
print(f"处理后的数据: {processed}")
print(f"统计信息: {stats}")

12.总结

内置函数是Python编程的基础工具,掌握这些函数的使用方法对于编写高效、简洁的Python代码至关重要。通过合理使用内置函数,我们可以:

  • 提高代码效率:内置函数通常比手动实现更快
  • 简化代码逻辑:减少重复代码,提高可读性
  • 保证代码质量:使用经过充分测试的标准函数
  • 提高开发效率:无需重复造轮子

12.1.学习建议

  1. 分类学习:按功能分类学习内置函数
  2. 实践应用:在实际项目中多使用内置函数
  3. 组合使用:学会将多个内置函数组合使用
  4. 性能考虑:了解内置函数的性能特点
  5. 错误处理:掌握内置函数的异常处理

掌握内置函数是成为优秀Python程序员的重要一步,它们为我们的编程工作提供了强大而便捷的工具。