Python--内置函数与推导式(下)

3. 内置函数

数学运算类

函数 说明 示例
​abs​ 绝对值 ​abs(-10) → 10​
​pow​ 幂运算 ​pow(2, 3) → 8​
​sum​ 求和 ​sum([1,2,3]) → 6​
​divmod​ 返回商和余数 ​divmod(10, 3) → (3, 1)​

数据转换类

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

# 字符与编码转换
print(ord('A'))   # 65  
print(chr(97))    # 'a'

迭代与序列操作类

函数 说明 示例
​enumerate​ 带索引的迭代 ​for i, v in enumerate(['a','b']):​
​zip​ 多序列并行迭代 ​list(zip([1,2], ['a','b']))​
​sorted​ 排序(支持自定义Key) ​sorted([3,1,2], reverse=True)​

其他实用函数

# 判断可调用对象
print(callable(len))  # True

# 哈希值计算
print(hash("Hello"))  # 随机整数(Python进程唯一)

4. 推导式

列表推导式

# 过滤偶数并平方
squares = [x**2 for x in range(10) if x % 2 == 0]
print(squares)  # [0, 4, 16, 36, 64]

字典推导式

# 反转键值对
original = {'a': 1, 'b': 2}
reversed_dict = {v: k for k, v in original.items()}
print(reversed_dict)  # {1: 'a', 2: 'b'}

集合推导式

# 去重后大写
words = {"hello", "world", "hello"}
upper_words = {word.upper() for word in words}
print(upper_words)  # {'HELLO', 'WORLD'}

生成器表达式(元组推导式)

gen = (x * 2 for x in range(3))
print(tuple(gen))  # (0, 2, 4)

嵌套推导式

# 生成3x3矩阵
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)  # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

5. 扩展知识

生成器与内存优化

  • 场景:处理10GB日志文件时,逐行读取避免内存溢出

    def read_large_file(file_path):
        with open(file_path, 'r') as f:
            for line in f:
                yield line.strip()
    

内置函数functools​模块

  • reduce​:累积计算(需导入)

    from functools import reduce
    product = reduce(lambda x, y: x * y, [1, 2, 3, 4])  # 24
    

你可能感兴趣的:(Python安全开发,python,开发语言,windows,网络安全,web安全,笔记,学习)