Skip to main content
 首页 » 编程设计

python之从两个嵌套列表创建元组列表

2025年05月04日15Terrylee

具有任意嵌套度的列表A,以及嵌套结构与A相同的列表B(或更深),我们如何为所有对应元素创建一个元组列表?例如:

A = ['a', ['b', ['c', 'd']], 'e']  
B = [1, [2, [3, [4, 5]]], 6] 
>>> 
[('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)] 

请您参考如下方法:

基本上,您需要做的就是同时迭代 a 和 b 并返回 a 和 b,如果 a 的当前元素不是列表。由于您的结构是嵌套的,我们无法线性迭代它们。这就是我们使用递归的原因。

此解决方案假定 A 中的每个元素在 B 中始终有对应的元素。

def rec(a, b): 
    if isinstance(a, list): 
        # If `a` is a list 
        for index, item in enumerate(a): 
            # then recursively iterate it 
            for items in rec(item, b[index]): 
                yield items 
    else: 
        # If `a` is not a list, just yield the current `a` and `b` 
        yield a, b 
 
print(list(rec(['a', ['b', ['c', 'd']], 'e'], [1, [2, [3, [4, 5]]], 6]))) 
# [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]