You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何实现嵌套列表的动态扁平化视图?

实现动态适配原嵌套列表修改的扁平化视图

可以通过自定义一个遵循Python序列协议的类来实现这种动态扁平化视图——该类不存储扁平化后的快照,而是实时从原嵌套列表中读取数据,确保任何对原列表的修改都会立刻反映在视图中。

代码实现

from collections.abc import Sequence

class FlatView(Sequence):
    def __init__(self, nested_iterables):
        # 保存原嵌套结构的引用,不做任何拷贝操作
        self.nested = nested_iterables

    def __len__(self):
        # 实时计算所有子容器的长度总和
        total_length = 0
        for sub_container in self.nested:
            total_length += len(sub_container)
        return total_length

    def __getitem__(self, index):
        # 处理整数索引(支持正负索引)
        if isinstance(index, int):
            # 转换负索引为正索引
            if index < 0:
                index += len(self)
            if index < 0 or index >= len(self):
                raise IndexError("FlatView index out of range")
            
            current_offset = 0
            for sub_container in self.nested:
                sub_len = len(sub_container)
                if current_offset + sub_len > index:
                    return sub_container[index - current_offset]
                current_offset += sub_len
        # 处理切片操作
        elif isinstance(index, slice):
            start, stop, step = index.indices(len(self))
            result = []
            for i in range(start, stop, step):
                result.append(self[i])
            return result
        else:
            raise TypeError("Index must be integer or slice")

    def __repr__(self):
        # 打印视图时展示当前扁平化后的内容
        return f"FlatView({list(self)})"

使用示例

a = ["a", "b", "c"]
b = ["d", "e", "f"]
view = FlatView([a, b])

# 初始状态
print(list(view))  # 输出: ['a', 'b', 'c', 'd', 'e', 'f']
print(view[3])     # 输出: 'd'

# 修改原列表元素
b[0] = "x"
print(list(view))  # 输出: ['a', 'b', 'c', 'x', 'e', 'f']
print(view[3])     # 输出: 'x'

# 给原列表添加元素
a.append("g")
print(len(view))   # 输出: 7
print(list(view))  # 输出: ['a', 'b', 'c', 'g', 'x', 'e', 'f']

# 从原列表删除元素
b.remove("e")
print(list(view))  # 输出: ['a', 'b', 'c', 'g', 'x', 'f']

核心特性说明

  • 实时同步:所有操作(索引访问、长度计算、迭代)都会实时遍历原嵌套结构,完全反映原列表的最新状态
  • 轻量无拷贝:仅保存原嵌套列表的引用,不占用额外内存存储扁平化数据
  • 兼容标准序列操作:继承Sequence抽象基类,自动支持in判断、iter()迭代、index()查找、count()统计等标准列表操作
  • 灵活适配:支持任何实现了__len__和__getitem__的可变子容器(如list、collections.deque等),子容器可自由修改、伸缩

内容的提问来源于stack exchange,提问作者mara004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 22:07:25