当前位置:首页 > Python > 正文

Python 56个内置函数详解(五) - zip/sorted/slice/staticmethod函数解析 | Python编程教程

Python 56个内置函数详解(五)

这是Python内置函数详解系列的第五部分,我们将深入探讨zip()sorted()slice()staticmethod()等核心内置函数。这些函数在数据处理、算法实现和面向对象编程中扮演着重要角色。

1 zip() 函数

功能: 将多个可迭代对象中对应的元素打包成一个个元组,返回一个zip对象

典型应用场景: 同时遍历多个列表、字典键值对转换、矩阵转置

基础用法

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

# 将两个列表组合
zipped = zip(names, ages)
print(list(zipped))  
# 输出: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

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

高级用法:解包操作

# 矩阵转置
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

transposed = list(zip(*matrix))
print(transposed)
# 输出: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

# 字典键值对转换
person = {'name': 'Alice', 'age': 25, 'job': 'Engineer'}
keys, values = zip(*person.items())
print(keys)    # ('name', 'age', 'job')
print(values)  # ('Alice', 25, 'Engineer')

2 sorted() 函数

功能: 对所有可迭代对象进行排序,返回一个新的列表

特点: 不改变原始数据,支持复杂排序条件

基础排序

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

# 默认升序排序
ascending = sorted(numbers)
print(ascending)  # [1, 1, 2, 3, 4, 5, 6, 9]

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

自定义排序

students = [
    {'name': 'Alice', 'grade': 85},
    {'name': 'Bob', 'grade': 92},
    {'name': 'Charlie', 'grade': 78}
]

# 按成绩排序
by_grade = sorted(students, key=lambda s: s['grade'])
print(by_grade)
# [{'name': 'Charlie', 'grade': 78}, ...]

# 多条件排序:先按成绩降序,再按姓名升序
multi_sorted = sorted(students, key=lambda s: (-s['grade'], s['name']))
print(multi_sorted)
# [{'name': 'Bob', 'grade': 92}, {'name': 'Alice', 'grade': 85}, ...]

3 slice() 函数

功能: 创建一个切片对象,用于序列的切片操作

使用场景: 动态生成切片、可复用的切片配置

基本使用

data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# 创建切片对象
first_five = slice(0, 5)
middle = slice(3, 7)
every_other = slice(0, None, 2)

print(data[first_five])  # [0, 1, 2, 3, 4]
print(data[middle])      # [3, 4, 5, 6]
print(data[every_other]) # [0, 2, 4, 6, 8]

高级应用

# 动态切片配置
def get_slice(data, start=None, stop=None, step=None):
    s = slice(start, stop, step)
    return data[s]

matrix = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12]
]

# 获取第二列
col_slice = slice(1, 2)
col_2 = [row[col_slice] for row in matrix]
print(col_2)  # [[2], [6], [10]]

4 staticmethod() 函数

功能: 将方法转换为静态方法,不需要实例即可调用

使用场景: 工具方法、与类相关但不依赖实例的方法

定义静态方法

class MathUtils:
    @staticmethod
    def add(a, b):
        return a + b
    
    @staticmethod
    def multiply(a, b):
        return a * b

# 无需创建实例即可调用
print(MathUtils.add(5, 3))       # 8
print(MathUtils.multiply(5, 3))  # 15

静态方法 vs 类方法

class MyClass:
    class_attr = "Class Attribute"
    
    @classmethod
    def class_method(cls):
        print(f"访问类属性: {cls.class_attr}")
    
    @staticmethod
    def static_method():
        print("静态方法不能访问类属性或实例属性")

MyClass.class_method()   # 访问类属性: Class Attribute
MyClass.static_method()  # 静态方法不能访问类属性或实例属性

总结

  • zip() 是处理并行迭代的强大工具
  • sorted() 提供了灵活的排序功能,支持多条件排序
  • slice() 允许创建可复用的切片配置
  • staticmethod() 用于创建不依赖类实例的工具方法

掌握这些内置函数能极大提升Python编程效率,建议在实际项目中多加练习!

发表评论