一文带你掌握5个鲜为人知的Python内置函数

作者:

文章目录
  • 为什么需要它们? 当你需要检查一个序列中是否"存在某个条件"或"所有元素都满足某个条件"时,any()和all()能让你告别冗长的循环。 基本用法 # any(): 只要有一个为True,就返回True numbers = [0, 2, 4, 6, 8] has_odd = any(n % 2 != 0 for n in numbers) # False # all(): 所有元素都为True,才返回True all_positive = all(n > 0 for n in numbers) # False (0不是正数) 实战案例 场景1:表单验证 # 传统写法 def validate_user(user): if not user.get(‘name’): return False if not user.get(’email’): return False if not user.get(‘age’): return False return True # 使用 all() – 简洁明了 def validate_user(user): required_fields = [‘name’, ’email’, ‘age’] return all(user.get(field) for field in required_fields) 场景2:权限检查 # 检查用户是否拥有任一管理员权限 permissions = [‘read’, ‘write’, ‘delete’] admin_permissions = [‘admin’, ‘superuser’, ‘delete’] is_admin = any(perm in admin_permissions for perm in permissions) 性能优势 any()和all()支持短路求值,一旦确定结果就立即返回,不会遍历整个序列,在处理大数据集时效率显著提升。
  • 为什么需要它? 在遍历列表时,如果既需要元素值又需要索引,enumerate()能让你摆脱笨拙的计数器。 基本用法 fruits = [‘apple’, ‘banana’, ‘cherry’] # 传统写法 index = 0 for fruit in fruits: print(f”{index}: {fruit}”) index += 1 # 使用 enumerate() – 优雅简洁 for index, fruit in enumerate(fruits): print(f”{index}: {fruit}”) 进阶技巧 自定义起始索引 # 从1开始编号(比如显示排名) for rank, player in enumerate(players, start=1): print(f”第{rank}名: {player}”) 同时获取多个序列的索引和值 names = [‘Alice’, ‘Bob’, ‘Charlie’] scores = [95, 87, 92] for i, (name, score) in enumerate(zip(names, scores)): print(f”学生{i+1}: {name} – {score}分”) 实战案例:查找所有匹配项的位置 # 找出列表中所有偶数的索引 numbers = [1, 4, 7, 8, 10, 3, 6] even_indices = [i for i, n in enumerate(numbers) if n % 2 == 0] # 结果: [1, 3, 4, 6]
  • 为什么需要它? 当你需要同时遍历多个列表,或将多个列表"打包"在一起时,zip()是最佳选择。 基本用法 names = [‘Alice’, ‘Bob’, ‘Charlie’] ages = [25, 30, 35] cities = [‘Beijing’, ‘Shanghai’, ‘Shenzhen’] for name, age, city in zip(names, ages, cities): print(f”{name}, {age}岁, 来自{city}”) 强大功能 1. 创建字典 keys = [‘name’, ‘age’, ’email’] values = [‘Alice’, 25, ‘alice@example.com’] user_dict = dict(zip(keys, values)) # {‘name’: ‘Alice’, ‘age’: 25, ’email’: ‘alice@example.com’} 2. 矩阵转置 matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] transposed = list(zip(*matrix)) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 3. 成对处理相邻元素 numbers = [1, 2, 3, 4, 5] # 计算相邻元素的差值 differences = [b – a for a, b in zip(numbers, numbers[1:])] # [1, 1, 1, 1] 注意事项 zip()会在最短序列结束时停止,如果需要填充缺失值,可以使用itertools.zip_longest()。
  • 为什么需要它? 当你需要同时得到除法的商和余数时,divmod()比分别调用//和%更高效(只需要一次除法运算)。 基本用法 quotient, remainder = divmod(17, 5) # quotient = 3, remainder = 2 实战案例 场景1:时间格式转换 def seconds_to_time(seconds): minutes, secs = divmod(seconds, 60) hours, mins = divmod(minutes, 60) return f”{hours:02d}:{mins:02d}:{secs:02d}” print(seconds_to_time(3665)) # “01:01:05″ 场景2:分页计算 def calculate_pagination(total_items, items_per_page): total_pages, extra = divmod(total_items, items_per_page) if extra > 0: total_pages += 1 return total_pages pages = calculate_pagination(97, 10) # 10页 场景3:货币换算 def convert_cents(total_cents): dollars, cents = divmod(total_cents, 100) return f”${dollars}.{cents:02d}” print(convert_cents(1234)) # “$12.34” 性能对比 # 传统方法(两次运算) q = a // b r = a % b # divmod(一次运算) q, r = divmod(a, b) # 更快!
  • 为什么需要它们? 当你需要根据字符串动态访问或修改对象属性时,这三个函数能让你的代码更灵活、更具扩展性。 基本用法 class User: def __init__(self): self.name = “Alice” self.age = 25 user = User() # getattr(): 动态获取属性 name = getattr(user, ‘name’) # “Alice” # 提供默认值避免AttributeError email = getattr(user, ’email’, ‘N/A’) # “N/A” # setattr(): 动态设置属性 setattr(user, ’email’, ‘alice@example.com’) # hasattr(): 检查属性是否存在 if hasattr(user, ‘phone’): print(user.phone) 实战案例 场景1:配置管理 class Config: def __init__(self): self.debug = False self.database = ‘sqlite’ self.port = 8000 def update_config(config, updates): “””根据字典批量更新配置””” for key, value in updates.items(): if hasattr(config, key): setattr(config, key, value) else: print(f”警告: 未知配置项 {key}”) config = Config() update_config(config, {‘debug’: True, ‘port’: 9000, ‘unknown’: ‘value’}) 场景2:表单数据映射 class Product: def __init__(self, **kwargs): # 动态设置所有传入的属性 for key, value in kwargs.items(): setattr(self, key, value) product = Product(name=”Laptop”, price=999, stock=50) print(product.name) # “Laptop” 场景3:API响应处理 def safe_get_nested(obj, path, default=None): “””安全地获取嵌套属性,例如 ‘user.profile.email'””” keys = path.split(‘.’) for key in keys: if hasattr(obj, key): obj = getattr(obj, key) else: return default return obj # 使用示例 value = safe_get_nested(user, ‘profile.settings.theme’, ‘light’) 场景4:通用数据导出 def export_to_dict(obj, fields): “””将对象的指定字段导出为字典””” return { field: getattr(obj, field, None) for field in fields } user_data = export_to_dict(user, [‘name’, ‘age’, ’email’])
  • 这5个内置函数看似简单,却能在实际开发中显著提升代码质量: 函数 核心优势 适用场景 any() / all() 短路求值,简化逻辑判断 数据验证、权限检查 enumerate() 同时获取索引和值 需要位置信息的遍历 zip() 并行处理多个序列 数据合并、矩阵操作 divmod() 一次运算得到商和余数 时间转换、分页计算 getattr() 系列 动态属性操作 配置管理、通用处理 最佳实践建议: 可读性优先:虽然这些函数能让代码更简洁,但不要为了炫技而牺牲可读性 性能考量:在处理大数据集时,这些函数的性能优势会更加明显 组合使用:这些函数可以互相配合,创造更强大的功能 了解限制:例如zip()在不等长序列的行为,getattr()需要处理不存在属性的情况 掌握这些函数,你的Python代码将更加Pythonic、高效和优雅。现在就去试试吧! 到此这篇关于一文带你掌握5个鲜为人知的Python内置函数的文章就介绍到这了,更多相关Python内置函数内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客! 您可能感兴趣的文章: 使用Python开发一个内置函数大全解析工具(附源码) Python内置函数之raise函数详解与实战案例 Python内置函数之classmethod函数使用详解 Python内置函数之property函数用法详解 详解Python中最常用的10个内置函数 Python中常见的内置函数使用讲解 Python中集合的内置函数详解
  • 目录
    • 1.any()和all()- 逻辑判断的利器
    • 2.enumerate()- 告别手动计数
    • 3.zip()- 并行处理多个序列
    • 4.divmod()- 一次性获取商和余数
    • 5.getattr()/setattr()/hasattr()- 动态属性操作
    • 总结

    作为Python开发者,我们经常使用print()len()range()等常见内置函数。但Python标准库中还隐藏着许多强大却被低估的内置函数,它们能让你的代码更简洁、更高效、更Pythonic。今天,我将分享5个你可能不太熟悉,但绝对值得掌握的内置函数。

    为什么需要它们?

    当你需要检查一个序列中是否"存在某个条件"或"所有元素都满足某个条件"时,any()all()能让你告别冗长的循环。

    基本用法

    # any(): 只要有一个为True,就返回True
    numbers = [0, 2, 4, 6, 8]
    has_odd = any(n % 2 != 0 for n in numbers)  # False
    
    # all(): 所有元素都为True,才返回True
    all_positive = all(n > 0 for n in numbers)  # False (0不是正数)
    

    实战案例

    场景1:表单验证

    # 传统写法
    def validate_user(user):
        if not user.get('name'):
            return False
        if not user.get('email'):
            return False
        if not user.get('age'):
            return False
        return True
    
    # 使用 all() - 简洁明了
    def validate_user(user):
        required_fields = ['name', 'email', 'age']
        return all(user.get(field) for field in required_fields)
    

    场景2:权限检查

    # 检查用户是否拥有任一管理员权限
    permissions = ['read', 'write', 'delete']
    admin_permissions = ['admin', 'superuser', 'delete']
    is_admin = any(perm in admin_permissions for perm in permissions)
    

    性能优势

    any()all()支持短路求值,一旦确定结果就立即返回,不会遍历整个序列,在处理大数据集时效率显著提升。

    为什么需要它?

    在遍历列表时,如果既需要元素值又需要索引,enumerate()能让你摆脱笨拙的计数器。

    基本用法

    fruits = ['apple', 'banana', 'cherry']
    
    # 传统写法
    index = 0
    for fruit in fruits:
        print(f"{index}: {fruit}")
        index += 1
    
    # 使用 enumerate() - 优雅简洁
    for index, fruit in enumerate(fruits):
        print(f"{index}: {fruit}")
    

    进阶技巧

    自定义起始索引

    # 从1开始编号(比如显示排名)
    for rank, player in enumerate(players, start=1):
        print(f"第{rank}名: {player}")
    

    同时获取多个序列的索引和值

    names = ['Alice', 'Bob', 'Charlie']
    scores = [95, 87, 92]
    
    for i, (name, score) in enumerate(zip(names, scores)):
        print(f"学生{i+1}: {name} - {score}分")
    

    实战案例:查找所有匹配项的位置

    # 找出列表中所有偶数的索引
    numbers = [1, 4, 7, 8, 10, 3, 6]
    even_indices = [i for i, n in enumerate(numbers) if n % 2 == 0]
    # 结果: [1, 3, 4, 6]
    

    为什么需要它?

    当你需要同时遍历多个列表,或将多个列表"打包"在一起时,zip()是最佳选择。

    基本用法

    names = ['Alice', 'Bob', 'Charlie']
    ages = [25, 30, 35]
    cities = ['Beijing', 'Shanghai', 'Shenzhen']
    
    for name, age, city in zip(names, ages, cities):
        print(f"{name}, {age}岁, 来自{city}")
    

    强大功能

    1. 创建字典

    keys = ['name', 'age', 'email']
    values = ['Alice', 25, 'alice@example.com']
    user_dict = dict(zip(keys, values))
    # {'name': 'Alice', 'age': 25, 'email': 'alice@example.com'}
    

    2. 矩阵转置

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

    3. 成对处理相邻元素

    numbers = [1, 2, 3, 4, 5]
    # 计算相邻元素的差值
    differences = [b - a for a, b in zip(numbers, numbers[1:])]
    # [1, 1, 1, 1]
    

    注意事项

    zip()会在最短序列结束时停止,如果需要填充缺失值,可以使用itertools.zip_longest()

    为什么需要它?

    当你需要同时得到除法的商和余数时,divmod()比分别调用//%更高效(只需要一次除法运算)。

    基本用法

    quotient, remainder = divmod(17, 5)
    # quotient = 3, remainder = 2
    

    实战案例

    场景1:时间格式转换

    def seconds_to_time(seconds):
        minutes, secs = divmod(seconds, 60)
        hours, mins = divmod(minutes, 60)
        return f"{hours:02d}:{mins:02d}:{secs:02d}"
    
    print(seconds_to_time(3665))  # "01:01:05"
    

    场景2:分页计算

    def calculate_pagination(total_items, items_per_page):
        total_pages, extra = divmod(total_items, items_per_page)
        if extra > 0:
            total_pages += 1
        return total_pages
    
    pages = calculate_pagination(97, 10)  # 10页
    

    场景3:货币换算

    def convert_cents(total_cents):
        dollars, cents = divmod(total_cents, 100)
        return f"${dollars}.{cents:02d}"
    
    print(convert_cents(1234))  # "$12.34"
    

    性能对比

    # 传统方法(两次运算)
    q = a // b
    r = a % b
    
    # divmod(一次运算)
    q, r = divmod(a, b)  # 更快!
    

    为什么需要它们?

    当你需要根据字符串动态访问或修改对象属性时,这三个函数能让你的代码更灵活、更具扩展性。

    基本用法

    class User:
        def __init__(self):
            self.name = "Alice"
            self.age = 25
    
    user = User()
    
    # getattr(): 动态获取属性
    name = getattr(user, 'name')  # "Alice"
    # 提供默认值避免AttributeError
    email = getattr(user, 'email', 'N/A')  # "N/A"
    
    # setattr(): 动态设置属性
    setattr(user, 'email', 'alice@example.com')
    
    # hasattr(): 检查属性是否存在
    if hasattr(user, 'phone'):
        print(user.phone)
    

    实战案例

    场景1:配置管理

    class Config:
        def __init__(self):
            self.debug = False
            self.database = 'sqlite'
            self.port = 8000
    
    def update_config(config, updates):
        """根据字典批量更新配置"""
        for key, value in updates.items():
            if hasattr(config, key):
                setattr(config, key, value)
            else:
                print(f"警告: 未知配置项 {key}")
    
    config = Config()
    update_config(config, {'debug': True, 'port': 9000, 'unknown': 'value'})
    

    场景2:表单数据映射

    class Product:
        def __init__(self, **kwargs):
            # 动态设置所有传入的属性
            for key, value in kwargs.items():
                setattr(self, key, value)
    
    product = Product(name="Laptop", price=999, stock=50)
    print(product.name)  # "Laptop"
    

    场景3:API响应处理

    def safe_get_nested(obj, path, default=None):
        """安全地获取嵌套属性,例如 'user.profile.email'"""
        keys = path.split('.')
        for key in keys:
            if hasattr(obj, key):
                obj = getattr(obj, key)
            else:
                return default
        return obj
    
    # 使用示例
    value = safe_get_nested(user, 'profile.settings.theme', 'light')
    

    场景4:通用数据导出

    def export_to_dict(obj, fields):
        """将对象的指定字段导出为字典"""
        return {
            field: getattr(obj, field, None) 
            for field in fields
        }
    
    user_data = export_to_dict(user, ['name', 'age', 'email'])
    

    这5个内置函数看似简单,却能在实际开发中显著提升代码质量:

    函数 核心优势 适用场景
    any() / all() 短路求值,简化逻辑判断 数据验证、权限检查
    enumerate() 同时获取索引和值 需要位置信息的遍历
    zip() 并行处理多个序列 数据合并、矩阵操作
    divmod() 一次运算得到商和余数 时间转换、分页计算
    getattr() 系列 动态属性操作 配置管理、通用处理

    最佳实践建议:

    • 可读性优先:虽然这些函数能让代码更简洁,但不要为了炫技而牺牲可读性
    • 性能考量:在处理大数据集时,这些函数的性能优势会更加明显
    • 组合使用:这些函数可以互相配合,创造更强大的功能
    • 了解限制:例如zip()在不等长序列的行为,getattr()需要处理不存在属性的情况

    掌握这些函数,你的Python代码将更加Pythonic、高效和优雅。现在就去试试吧!

    到此这篇关于一文带你掌握5个鲜为人知的Python内置函数的文章就介绍到这了,更多相关Python内置函数内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

    您可能感兴趣的文章:

    • 使用Python开发一个内置函数大全解析工具(附源码)
    • Python内置函数之raise函数详解与实战案例
    • Python内置函数之classmethod函数使用详解
    • Python内置函数之property函数用法详解
    • 详解Python中最常用的10个内置函数
    • Python中常见的内置函数使用讲解
    • Python中集合的内置函数详解

    站内搜索