Python 中的哪种类型的 iterable/list 能够在结构上与之前的 iterables/lists 共享相同的项目?

Which type of iterable/list in Python is able to structurally share the same items from previous iterables/lists?

假设我有两个长列表 ab 并且想要一个列表 c:

a = [obj1, obj2, ..., objN]
b = [objNplus1, objNplus2, ..., objNplusM]
c = a + b

我如何创建一个新的列表,它共享以前的列表作为它的开始和结束,但又不违反它们中任何一个的参照完整性,即不改变 ab;而且,也没有从头开始重新创建整个列表 c? 作为默认集合的一部分或作为外部包的一部分,是否有类似于这样的列表的东西?

我想它有点像一棵树,也许有一个模仿 DFS 的关联链表。

您可以使用 itertools.chain():

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.

例如:

import itertools
c = itertools.chain(a, b)

更新:要更接近地模拟 list,您可以编写自己的 class,例如:

class ListOfLists():
    def __init__(self, *args):
        self._lists = args
        self._len = sum(map(len, self._lists))

    def __iter__(self):
        for _list in self._lists:
            for item in _list:
                yield item

    def __getitem__(self, y):
        if y >= self._len:
            raise IndexError
        for l in self._lists:
            if y > len(l):
                y -= len(l)
            else:
                return l[y]

    def __len__(self):
        return self._len

a = [1, 2, 3]
b = ["a", "b", "c"]
c = ListOfLists(a, b)

print("Total length is", len(c))
print("4th element is", c[4])
for i, item in enumerate(c):
    print(i, ":", item)

输出:

Total length is 6
4th element is b
0 : 1
1 : 2
2 : 3
3 : a
4 : b
5 : c

您可能还应该实现其他方法(例如 __getslice__() 如果您需要切片)。此外,它不是递归的,这意味着您只能以其现有形式合并 "regular" list。如果将 ListOfLists 传递给构造函数,它将不起作用。