Python教程24:内置函数深入

“工欲善其事,必先利其器。”

Python提供了60多个内置函数(built-in functions),它们无需导入即可使用。今天我们深入学习最常用、最实用的内置函数,让你的代码更简洁高效。

1. 什么是内置函数

内置函数(Built-in Functions)

  • Python解释器自带的函数
  • 无需import即可直接使用
  • 用C语言实现,性能优异
  • 覆盖最常见的编程需求

查看所有内置函数

1# dir(__builtins__)会列出所有内置对象
2# __builtins__是Python内置命名空间
3import builtins
4print(dir(builtins))
5
6# 或者查看官方文档
7help(builtins)

我们已经用过很多内置函数:print()len()type()int()str()等。

2. 类型转换函数

基础类型转换

 1# int() - 转换为整数
 2# Python内置函数,将其他类型转为整数
 3print(int("123"))      # 123
 4print(int(3.14))       # 3(截断小数部分)
 5print(int("1010", 2))  # 10(二进制转十进制)
 6print(int("FF", 16))   # 255(十六进制转十进制)
 7
 8# float() - 转换为浮点数
 9print(float("3.14"))   # 3.14
10print(float("inf"))    # inf(无穷大)
11
12# str() - 转换为字符串
13print(str(123))        # "123"
14print(str([1, 2, 3]))  # "[1, 2, 3]"
15
16# bool() - 转换为布尔值
17# 遵循Python的真值规则
18print(bool(0))         # False
19print(bool(""))        # False
20print(bool([]))        # False
21print(bool("False"))   # True(非空字符串为True)

容器类型转换

 1# list() - 转换为列表
 2print(list("Python"))           # ['P', 'y', 't', 'h', 'o', 'n']
 3print(list(range(5)))           # [0, 1, 2, 3, 4]
 4print(list({1, 2, 3}))          # [1, 2, 3]
 5
 6# tuple() - 转换为元组
 7print(tuple([1, 2, 3]))         # (1, 2, 3)
 8print(tuple("abc"))             # ('a', 'b', 'c')
 9
10# set() - 转换为集合(自动去重)
11print(set([1, 2, 2, 3, 3, 3]))  # {1, 2, 3}
12print(set("hello"))             # {'h', 'e', 'l', 'o'}
13
14# dict() - 转换为字典
15print(dict([('a', 1), ('b', 2)]))  # {'a': 1, 'b': 2}
16print(dict(a=1, b=2))              # {'a': 1, 'b': 2}

3. 数学函数

 1# abs() - 绝对值
 2print(abs(-10))        # 10
 3print(abs(-3.14))      # 3.14
 4
 5# round() - 四舍五入
 6# 可以指定保留几位小数
 7print(round(3.14159))      # 3
 8print(round(3.14159, 2))   # 3.14
 9print(round(3.14159, 3))   # 3.142
10
11# pow() - 幂运算
12# pow(x, y) 等价于 x ** y
13# pow(x, y, z) 等价于 (x ** y) % z(高效)
14print(pow(2, 3))       # 8
15print(pow(2, 3, 5))    # 3(即 8 % 5)
16
17# sum() - 求和
18# 可以指定起始值
19print(sum([1, 2, 3, 4, 5]))         # 15
20print(sum([1, 2, 3], 10))           # 16(10 + 1 + 2 + 3)
21
22# min() / max() - 最小值/最大值
23print(min(1, 2, 3, 4, 5))           # 1
24print(max([1, 2, 3, 4, 5]))         # 5
25print(min("apple", "banana"))       # "apple"(字典序)
26
27# divmod() - 同时返回商和余数
28print(divmod(17, 5))   # (3, 2)

4. 序列操作函数

all() 和 any()

 1#all() - 所有元素为True时返回True
 2# Python内置函数,用于检查可迭代对象中所有元素
 3print(all([True, True, True]))     # True
 4print(all([True, False, True]))    # False
 5print(all([]))                     # True(空序列)
 6
 7# 实际应用:检查所有数字是否为正数
 8numbers = [1, 2, 3, 4, 5]
 9print(all(n > 0 for n in numbers)) # True
10
11# any() - 任一元素为True时返回True
12print(any([False, False, True]))   # True
13print(any([False, False, False]))  # False
14print(any([]))                     # False(空序列)
15
16# 实际应用:检查是否含有偶数
17print(any(n % 2 == 0 for n in numbers))  # True

sorted() 和 reversed()

 1# sorted() - 排序(返回新列表)
 2# 不修改原序列,返回排序后的新列表
 3numbers = [3, 1, 4, 1, 5, 9, 2, 6]
 4print(sorted(numbers))              # [1, 1, 2, 3, 4, 5, 6, 9]
 5print(sorted(numbers, reverse=True)) # [9, 6, 5, 4, 3, 2, 1, 1]
 6
 7# 按长度排序
 8words = ["python", "is", "awesome"]
 9print(sorted(words, key=len))       # ['is', 'python', 'awesome']
10
11# 按复杂规则排序
12students = [
13    {"name": "Alice", "score": 85},
14    {"name": "Bob", "score": 92},
15    {"name": "Charlie", "score": 78}
16]
17print(sorted(students, key=lambda x: x["score"], reverse=True))
18
19# reversed() - 反转(返回迭代器)
20print(list(reversed([1, 2, 3])))    # [3, 2, 1]
21print(list(reversed("Python")))     # ['n', 'o', 'h', 't', 'y', 'P']

zip() 和 enumerate()

 1# zip() - 并行打包多个序列
 2# Python内置函数,用于同时遍历多个序列
 3names = ["Alice", "Bob", "Charlie"]
 4ages = [25, 30, 35]
 5cities = ["Beijing", "Shanghai", "Guangzhou"]
 6
 7# 打包成元组列表
 8pairs = list(zip(names, ages, cities))
 9print(pairs)
10# [('Alice', 25, 'Beijing'), ('Bob', 30, 'Shanghai'), ('Charlie', 35, 'Guangzhou')]
11
12# 解包:zip的逆操作
13names2, ages2, cities2 = zip(*pairs)
14print(names2)  # ('Alice', 'Bob', 'Charlie')
15
16# enumerate() - 带索引遍历
17# 返回(索引, 值)的元组
18for i, fruit in enumerate(["apple", "banana", "cherry"]):
19    print(f"{i}: {fruit}")
20
21# 指定起始索引
22for i, fruit in enumerate(["apple", "banana"], start=1):
23    print(f"{i}. {fruit}")

5. 高阶函数

map()

 1# map() - 映射函数到序列
 2# apply函数到每个元素,返回迭代器
 3numbers = [1, 2, 3, 4, 5]
 4
 5# 平方
 6squares = map(lambda x: x**2, numbers)
 7print(list(squares))  # [1, 4, 9, 16, 25]
 8
 9# 字符串转大写
10words = ["hello", "world", "python"]
11upper_words = map(str.upper, words)
12print(list(upper_words))  # ['HELLO', 'WORLD', 'PYTHON']
13
14# 多个序列
15a = [1, 2, 3]
16b = [4, 5, 6]
17sums = map(lambda x, y: x + y, a, b)
18print(list(sums))  # [5, 7, 9]

filter()

 1# filter() - 过滤序列
 2# 保留使函数返回True的元素
 3numbers = range(1, 11)
 4
 5# 过滤出偶数
 6evens = filter(lambda x: x % 2 == 0, numbers)
 7print(list(evens))  # [2, 4, 6, 8, 10]
 8
 9# 过滤空字符串
10strings = ["hello", "",  "world", "", "python"]
11non_empty = filter(None, strings)  # None会过滤掉假值
12print(list(non_empty))  # ['hello', 'world', 'python']

6. 对象和属性函数

 1# id() - 对象的唯一标识(内存地址)
 2# Python内置函数,返回对象的身份标识
 3a = [1, 2, 3]
 4b = [1, 2, 3]
 5print(id(a))  # 140234567890123(示例)
 6print(id(b))  # 140234567890456(不同)
 7print(id(a) == id(b))  # False
 8
 9# isinstance() - 类型检查
10print(isinstance(42, int))           # True
11print(isinstance("hello", str))      # True
12print(isinstance([1, 2], (list, tuple)))  # True(多个类型)
13
14# hasattr() / getattr() / setattr() - 属性操作
15class Person:
16    def __init__(self, name):
17        self.name = name
18
19p = Person("Alice")
20print(hasattr(p, "name"))         # True
21print(getattr(p, "name"))         # "Alice"
22print(getattr(p, "age", 0))       # 0(默认值)
23setattr(p, "age", 25)
24print(p.age)                      # 25
25
26# dir() - 列出对象的所有属性和方法
27print(dir(str))  # 列出字符串的所有方法

7. 输入输出函数

 1# print() -输出
 2# sep参数:分隔符
 3print("a", "b", "c", sep="-")  # a-b-c
 4
 5# end参数:结束符(默认是换行)
 6print("Hello", end=" ")
 7print("World")  # Hello World
 8
 9# file参数:输出到文件
10with open("output.txt", "w") as f:
11    print("Hello", file=f)
12
13# input() - 获取用户输入
14# 返回字符串,需要转换类型
15name = input("请输入姓名:")
16age = int(input("请输入年龄:"))

8. 编译和执行函数

 1# eval() - 执行Python表达式字符串
 2# 警告:不要对不可信的输入使用eval()!
 3result = eval("1 + 2 * 3")
 4print(result)  # 7
 5
 6# exec() - 执行Python代码字符串
 7code = """
 8def greet(name):
 9    return f"Hello, {name}"
10print(greet("Alice"))
11"""
12exec(code)  # 输出:Hello, Alice
13
14# compile() - 编译代码
15# 用于需要多次执行同一代码的场景
16code_obj = compile("1 + 2", "<string>", "eval")
17print(eval(code_obj))  # 3

安全警告eval()exec()很危险,不要对用户输入使用!

9. 实用技巧

批量类型转换

1# 字符串列表转整数列表
2str_numbers = ["1", "2", "3", "4", "5"]
3int_numbers = list(map(int, str_numbers))
4print(int_numbers)  # [1, 2, 3, 4, 5]

字典推导式 + zip

1keys = ["name", "age", "city"]
2values = ["Alice", 25, "Beijing"]
3person = dict(zip(keys, values))
4print(person)  # {'name': 'Alice', 'age': 25, 'city': 'Beijing'}

统计元素出现次数

1from collections import Counter
2
3# 虽然有Counter,但也可以用内置函数
4items = ["a", "b", "a", "c", "b", "a"]
5counts = {item: items.count(item) for item in set(items)}
6print(counts)  # {'a': 3, 'b': 2, 'c': 1}

10. 小结

今天我们学习了Python的常用内置函数:

  • 类型转换:int、float、str、bool、list、tuple、set、dict
  • 数学运算:abs、round、pow、sum、min、max、divmod
  • 序列操作:all、any、sorted、reversed、zip、enumerate
  • 高阶函数:map、filter
  • 对象属性:id、isinstance、hasattr、getattr、setattr、dir
  • 输入输出:print、input
  • 执行代码:eval、exec、compile(谨慎使用)

掌握这些内置函数能让你的代码更简洁、更Pythonic。


练习题

  1. 用zip()和dict()将两个列表转换为字典
  2. 用map()和filter()组合处理数据
  3. 用all()检查一个列表是否所有元素都满足某条件

本文代码示例

关注公众号:极客老墨

更多 AI 应用开发、工程实践和效率工具分享,欢迎扫码关注。

极客老墨微信公众号二维码

相关阅读