当前位置:首页>python>Python 内置函数系列:l开头系列函数

Python 内置函数系列:l开头系列函数

  • 2026-10-21 13:27:18
Python 内置函数系列:l开头系列函数

len():长度计算的"尺子"

1. 基础用法:获取对象元素个数

len()函数返回对象的长度(元素个数),支持序列和集合等多种数据类型。

# 序列类型长度计算
string = "Hello World"
print
(f"字符串长度: {len(string)}")  # 输出: 11

list_data = [1, 2, 3, 4, 5]
print
(f"列表长度: {len(list_data)}")  # 输出: 5

tuple_data = (10, 20, 30)
print
(f"元组长度: {len(tuple_data)}")  # 输出: 3

# 集合类型长度计算

set_data = {1, 2, 3, 2, 1}  # 去重后
print
(f"集合长度: {len(set_data)}")  # 输出: 3

dict_data = {'a': 1, 'b': 2, 'c': 3}
print
(f"字典长度: {len(dict_data)}")  # 输出: 3

# 范围对象

range_obj = range(1, 10)
print
(f"范围对象长度: {len(range_obj)}")  # 输出: 9

2. 实际应用:数据验证和边界检查

class DataValidator:
    @staticmethod

    def
 validate_input_length(data, min_len=0, max_len=None):
        """验证输入数据长度"""

        data_len = len(data)

        if
 data_len < min_len:
            raise
 ValueError(f"数据长度不能小于{min_len}")

        if
 max_len is not None and data_len > max_len:
            raise
 ValueError(f"数据长度不能超过{max_len}")

        return
 True

    @staticmethod

    def
 chunk_data(data, chunk_size):
        """将数据分块"""

        if
 len(data) == 0:
            return
 []

        chunks = []
        for
 i in range(0, len(data), chunk_size):
            chunk = data[i:i + chunk_size]
            chunks.append(chunk)
        return
 chunks

    @staticmethod

    def
 compare_structures(struct1, struct2):
        """比较两个数据结构的长度"""

        len1 = len(struct1) if hasattr(struct1, '__len__') else 'N/A'
        len2 = len(struct2) if hasattr(struct2, '__len__') else 'N/A'

        return
 {
            'structure1_length'
: len1,
            'structure2_length'
: len2,
            'equal_length'
: len1 == len2 if isinstance(len1, int) and isinstance(len2, int) else False
        }

# 使用示例

validator = DataValidator()

# 长度验证

try
:
    validator.validate_input_length("hello", min_len=3, max_len=10)
    print
("长度验证通过")
except
 ValueError as e:
    print
(f"验证失败: {e}")

# 数据分块

data = list(range(20))
chunks = validator.chunk_data(data, chunk_size=5)
print
(f"数据分块: {chunks}")

# 结构比较

list1 = [1, 2, 3]
dict1 = {'a': 1, 'b': 2}
result = validator.compare_structures(list1, dict1)
print
(f"结构比较: {result}")

list():列表创建的"工厂"

1. 基础用法:创建列表对象

list()函数从可迭代对象创建新的列表,是Python中最常用的序列类型。

# 从字符串创建(字符列表)
chars = list("hello")
print
(f"字符串转列表: {chars}")  # 输出: ['h', 'e', 'l', 'l', 'o']

# 从元组创建

tuple_data = (1, 2, 3)
list_from_tuple = list(tuple_data)
print
(f"元组转列表: {list_from_tuple}")  # 输出: [1, 2, 3]

# 从范围对象创建

numbers = list(range(5))
print
(f"范围转列表: {numbers}")  # 输出: [0, 1, 2, 3, 4]

# 从集合创建(顺序可能不同)

set_data = {3, 1, 4, 2}
list_from_set = list(set_data)
print
(f"集合转列表: {list_from_set}")  # 输出: [1, 2, 3, 4](顺序可能变化)

# 空列表

empty_list = list()
print
(f"空列表: {empty_list}")  # 输出: []

# 从字典创建(只获取键)

dict_data = {'a': 1, 'b': 2}
keys_list = list(dict_data)
print
(f"字典键列表: {keys_list}")  # 输出: ['a', 'b']

2. 实际应用:数据转换和处理

class ListProcessor:
    @staticmethod

    def
 flatten_nested_lists(nested_list):
        """展平嵌套列表"""

        result = []
        for
 item in nested_list:
            if
 isinstance(item, list):
                result.extend(ListProcessor.flatten_nested_lists(item))
            else
:
                result.append(item)
        return
 result

    @staticmethod

    def
 remove_duplicates_preserve_order(sequence):
        """去重并保持顺序"""

        seen = set()
        return
 [x for x in sequence if not (x in seen or seen.add(x))]

    @staticmethod

    def
 batch_process(iterable, batch_size):
        """批量处理数据"""

        items = list(iterable)  # 确保是可迭代的
        batches = []
        for
 i in range(0, len(items), batch_size):
            batch = items[i:i + batch_size]
            batches.append(batch)
        return
 batches

    @staticmethod

    def
 create_index_map(data):
        """创建值到索引的映射"""

        index_map = {}
        for
 idx, value in enumerate(list(data)):
            if
 value not in index_map:
                index_map[value] = []
            index_map[value].append(idx)
        return
 index_map

# 使用示例

processor = ListProcessor()

# 展平嵌套列表

nested = [[1, 2], [3, [4, 5]], 6]
flat = processor.flatten_nested_lists(nested)
print
(f"展平结果: {flat}")

# 去重保持顺序

data_with_duplicates = [3, 1, 2, 1, 4, 2, 5]
unique_ordered = processor.remove_duplicates_preserve_order(data_with_duplicates)
print
(f"去重结果: {unique_ordered}")

# 批量处理

large_data = range(100)
batches = processor.batch_process(large_data, batch_size=10)
print
(f"批次数量: {len(batches)}")
print
(f"第一个批次: {batches[0]}")

# 索引映射

text = "hello"
index_map = processor.create_index_map(text)
print
(f"字符索引映射: {index_map}")

locals():局部变量的"镜子"

1. 基础用法:访问局部命名空间

locals()函数返回当前局部符号表的映射对象,反映当前作用域的变量状态。

def demonstrate_locals():
    """演示locals()函数的基本用法"""

    x = 10
    y = "hello"
    z = [1, 2, 3]

    # 获取局部变量字典

    local_vars = locals()
    print
("局部变量:")
    for
 var_name, var_value in local_vars.items():
        print
(f"  {var_name}: {var_value}")

    # 修改局部变量

    local_vars['x'] = 100
    local_vars['new_var'] = "动态添加"

    print
(f"修改后x的值: {x}")  # 输出: 100
    print
(f"新变量: {new_var}")  # 输出: 动态添加

    return
 local_vars

# 函数调用

local_dict = demonstrate_locals()
print
(f"返回的局部字典: {local_dict}")

# 模块级别的locals()(与globals()相同)

module_locals = locals()
module_globals = globals()
print
(f"模块级别locals和globals相同: {module_locals is module_globals}")  # 输出: True

2. 实际应用:调试和动态编程

class DebugHelper:
    def
 __init__(self):
        self
.snapshots = {}

    def
 take_snapshot(self, snapshot_name):
        """拍摄当前局部状态快照"""

        current_locals = locals().copy()
        # 移除self参数

        current_locals.pop('self', None)
        self
.snapshots[snapshot_name] = current_locals
        return
 current_locals

    def
 compare_snapshots(self, snap1_name, snap2_name):
        """比较两个快照的差异"""

        snap1 = self.snapshots.get(snap1_name, {})
        snap2 = self.snapshots.get(snap2_name, {})

        added = {k: v for k, v in snap2.items() if k not in snap1}
        removed = {k: v for k, v in snap1.items() if k not in snap2}
        changed = {}

        for
 k in set(snap1.keys()) & set(snap2.keys()):
            if
 snap1[k] != snap2[k]:
                changed[k] = (snap1[k], snap2[k])

        return
 {'added': added, 'removed': removed, 'changed': changed}

    def
 dynamic_variable_management(self, **kwargs):
        """动态变量管理"""

        current_locals = locals()
        print
("初始局部变量:", current_locals)

        # 动态添加变量

        for
 key, value in kwargs.items():
            locals
()[key] = value
            print
(f"已添加变量: {key} = {value}")

        # 注意:在函数中修改locals()可能不会影响实际变量

        # 这里主要用于演示


def
 test_function():
    """测试函数用于演示locals()行为"""

    debugger = DebugHelper()

    # 第一次快照

    a = 10
    b = 20
    debugger.take_snapshot("第一次")

    # 第二次快照(变量变化)

    a = 100
    c = "新变量"
    debugger.take_snapshot("第二次")

    # 比较差异

    differences = debugger.compare_snapshots("第一次", "第二次")
    print
("变量变化:", differences)

    # 动态管理

    debugger.dynamic_variable_management(x=1, y=2, z=3)

# 使用示例

test_function()

# 在推导式中的使用(Python 3.12+)

def
 demonstrate_comprehension_locals():
    """演示推导式中的locals()行为"""

    external_var = "外部变量"

    # 列表推导式

    result = [locals().get('external_var') for _ in range(3)]
    print
(f"推导式中的locals(): {result}")

    # 注意:在推导式中,locals()的行为可能因Python版本而异


demonstrate_comprehension_locals()

总结

本文介绍了Python中三个重要的内置函数:

  1. 1. len() - 长度计算的尺子,数据验证、边界检查、循环控制
  2. 2. list() - 列表创建的工厂,数据转换、序列处理、结果收集
  3. 3. locals() - 局部变量的镜子,调试工具、动态编程、状态检查

关键知识点总结:

  • • len(object)返回对象的元素个数,支持大多数容器类型
  • • list(iterable)从可迭代对象创建新列表,是常用的序列转换函数
  • • locals()返回当前局部命名空间的字典,但在不同作用域中行为有差异

最佳实践建议:

  1. 1. 长度检查优先:在处理容器前先用 len()检查大小
  2. 2. 适时使用list():需要修改或多次访问时,将可迭代对象转为列表
  3. 3. 谨慎使用locals():主要限于调试,生产代码中避免依赖其修改功能
  4. 4. 异常处理:对可能的大数据使用 len()时捕获 OverflowError

阅读推荐:

Python 内置函数系列:i开头系列函数

Python 内置函数系列:h开头系列函数

Python 内置函数系列:g开头系列函数


✨关注我,获取更多Python学习资源、实战项目和行业动态!在公众号后台回复"python学习",获取Python学习电子书籍!

最新文章

随机文章