目录

Python 常用内置函数

学习目标

  • 掌握 Python 常用内置函数的使用方法
  • 理解函数式编程工具:mapfilterreduce
  • 学会使用排序和聚合函数
  • 掌握类型转换和判断函数

1. 类型转换函数

# 数值转换
print(int("42"))          # 42
print(int(3.7))           # 3(截断小数)
print(float("3.14"))      # 3.14
print(bool(1))            # True
print(complex(3, 4))      # (3+4j)

# 序列转换
print(str(123))           # "123"
print(list("abc"))        # ['a', 'b', 'c']
print(tuple([1, 2, 3]))   # (1, 2, 3)
print(set([1, 2, 2, 3]))  # {1, 2, 3}
print(dict([("a", 1), ("b", 2)]))  # {'a': 1, 'b': 2}

# 字节转换
print(bytes("hello", "utf-8"))   # b'hello'
print(ord("A"))                  # 65
print(chr(65))                   # 'A'

2. 数学函数

# 绝对值和取整
print(abs(-10))           # 10
print(round(3.7))         # 4
print(round(3.14159, 2))  # 3.14
print(divmod(17, 5))      # (3, 2) 商和余数
print(pow(2, 10))         # 1024(2的10次方)
print(pow(2, 3, 5))       # 3(2^3 % 5)

# 最值和求和
numbers = [3, 1, 4, 1, 5, 9]
print(max(numbers))       # 9
print(min(numbers))       # 1
print(sum(numbers))       # 23

# 带key的最值
words = ["apple", "banana", "cherry"]
print(max(words, key=len))  # banana(最长)
print(min(words, key=len))  # apple(最短)

3. 序列操作函数

3.1 len、range、enumerate

# len - 长度
print(len("hello"))       # 5
print(len([1, 2, 3]))     # 3
print(len({"a": 1, "b": 2}))  # 2

# range - 范围
print(list(range(5)))      # [0, 1, 2, 3, 4]
print(list(range(1, 6)))   # [1, 2, 3, 4, 5]
print(list(range(0, 10, 2)))  # [0, 2, 4, 6, 8]

# enumerate - 枚举
fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits, 1):
    print(f"{i}. {fruit}")

3.2 zip 和 reversed

# zip - 并行迭代
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name}: {age}岁")

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

# zip_longest(itertools)
from itertools import zip_longest
list1 = [1, 2]
list2 = ["a", "b", "c"]
for x, y in zip_longest(list1, list2, fillvalue="-"):
    print(x, y)

# reversed - 反转
print(list(reversed([1, 2, 3])))  # [3, 2, 1]
for char in reversed("hello"):
    print(char, end="")  # olleh

3.3 sorted 排序

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

# 基本排序
print(sorted(numbers))              # [1, 1, 2, 3, 4, 5, 6, 9]
print(sorted(numbers, reverse=True)) # [9, 6, 5, 4, 3, 2, 1, 1]

# 自定义排序
words = ["banana", "pie", "Washington", "book"]
print(sorted(words, key=len))       # ['pie', 'book', 'banana', 'Washington']
print(sorted(words, key=str.lower)) # ['banana', 'book', 'pie', 'Washington']

# 多级排序
data = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 30},
    {"name": "Charlie", "age": 25},
]

# 先按年龄,再按姓名
sorted_data = sorted(data, key=lambda x: (x["age"], x["name"]))
print(sorted_data)

4. 函数式编程工具

4.1 map - 映射

# map(function, iterable)
numbers = [1, 2, 3, 4, 5]

# 平方
squares = list(map(lambda x: x**2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# 多参数
list1 = [1, 2, 3]
list2 = [10, 20, 30]
sums = list(map(lambda x, y: x + y, list1, list2))
print(sums)  # [11, 22, 33]

# 等价于列表推导式
squares2 = [x**2 for x in numbers]
print(squares2)

4.2 filter - 过滤

# filter(function, iterable)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# 偶数
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)  # [2, 4, 6, 8, 10]

# 非空字符串
words = ["", "hello", "", "world", "  "]
non_empty = list(filter(None, words))  # None 等价于 bool
print(non_empty)  # ['hello', 'world', '  ']

# 等价于列表推导式
evens2 = [x for x in numbers if x % 2 == 0]
print(evens2)

4.3 reduce - 归约

from functools import reduce

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

# 求和
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 15

# 阶乘
factorial = reduce(lambda x, y: x * y, range(1, 6))
print(factorial)  # 120

# 找最大值
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum)  # 5

# 带初始值
result = reduce(lambda x, y: x + y, numbers, 100)
print(result)  # 115

5. 对象操作函数

5.1 hasattr、getattr、setattr、delattr

class Person:
    name = "小明"
    age = 25

p = Person()

# 检查属性
print(hasattr(p, "name"))   # True
print(hasattr(p, "gender")) # False

# 获取属性
print(getattr(p, "name"))               # 小明
print(getattr(p, "gender", "未知"))      # 未知(默认值)

# 设置属性
setattr(p, "gender", "男")
print(p.gender)  # 男

# 删除属性
delattr(p, "gender")

5.2 isinstance、issubclass、type

class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()

# 类型检查
print(type(dog))                 # <class '__main__.Dog'>
print(isinstance(dog, Dog))      # True
print(isinstance(dog, Animal))   # True(考虑继承)
print(isinstance(dog, (int, str, Dog)))  # True

# 子类检查
print(issubclass(Dog, Animal))   # True
print(issubclass(Dog, Dog))      # True

5.3 id、hash、dir

# id - 对象唯一标识
a = [1, 2, 3]
print(id(a))

# hash - 哈希值(可变对象不能hash)
print(hash("hello"))
print(hash((1, 2, 3)))
# print(hash([1, 2, 3]))  # TypeError

# dir - 对象的属性和方法
print(dir(str))  # 字符串的所有方法
print(dir([]))   # 列表的所有方法

6. 输入输出函数

# print
print("hello", "world", sep="-", end="!\n")

# input(交互式)
# name = input("请输入名字: ")
# print(f"你好, {name}")

# open
with open("test.txt", "w") as f:
    f.write("hello")

# repr - 对象的规范字符串表示
print(repr("hello\n"))  # 'hello\n'
print(str("hello\n"))   # hello(换行)

7. 其他实用函数

# all / any
print(all([True, True, False]))  # False
print(all([1, 2, 3]))            # True(非零为真)
print(any([False, False, True])) # True
print(any([0, "", None]))        # False

# bin / oct / hex
print(bin(10))   # 0b1010
print(oct(10))   # 0o12
print(hex(10))   # 0xa

# eval / exec(谨慎使用)
x = 1
print(eval("x + 1"))  # 2

# exec("print('hello')")  # 执行语句

# isinstance + 类型检查
numbers = [1, "2", 3, "4", 5]
integers = list(filter(lambda x: isinstance(x, int), numbers))
print(integers)  # [1, 3, 5]

# callable
print(callable(print))    # True
print(callable(123))      # False
print(callable(lambda: 1)) # True

# globals / locals
print(globals().keys())   # 全局变量

本节小结

  • 类型转换intstrlistdict
  • 数学函数absroundmaxminsum
  • 序列操作lenrangeenumeratezipreversedsorted
  • 函数式mapfilterreduce(functools)
  • 对象操作hasattrgetattrisinstancetype
  • 实用函数allanybinhexcallable

练习

  1. 使用 mapfilter 将列表中所有奇数平方
  2. 使用 reduce 实现字符串列表的拼接
  3. 编写函数,使用 zip 将两个字典合并
  4. 使用 sorted 对复杂对象列表按多个字段排序