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

Create a list of tuples from two nested lists

具有任意嵌套程度的列表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)]

你想要一个递归压缩函数:

from itertools import izip
def recurse_zip(a, b):
    zipped = izip(a, b)
    for t in zipped:
        if isinstance(t[0], list):
            for item in recurse_zip(*t):
                yield item
        else:
            yield t

演示:

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

备注:

  • izip 有助于使其变懒——python3.x 的 zip 也可以。
  • 可以在 python3.3+ (yield from recurse_zip(*t)).
  • 中使用 yield from 语法
  • 发电机很棒。

您可以使用 zip 进行迭代以创建列表,

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

def make_tuples(list1, list2):
    tups = []
    def _helper(l1, l2):
        for a, b in zip(l1, l2):
            if isinstance(a, list) and isinstance(b, list):
                _helper(a, b)
            else:
                tups.append((a, b))
    _helper(list1, list2)
    return tups

make_tuples(A, B)

或者一个简单的元组生成器 -

def tuples_generator(l1, l2):
    for a, b in zip(l1, l2):
        if isinstance(a, list) and isinstance(b, list):
            tuples_generator(a, b)
        else:
            yield (a, b)

In : make_tuples(A, B)
Out: [('a', 1), ('b', 2), ('c', 3), ('d', [4, 5]), ('e', 6)]

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

此解决方案假设 B 中的每个元素始终对应于 A 中的每个元素。

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)]

你可以使用zip,这是我的答案。

a = ['a', ['b', ['c', 'd']], 'e']
b = [1, [2, [3, [4, 5]]], 6]
c = []

def CheckIfList(a):
    for k in a:
        print 'k is:', k
        if isinstance(k, (list, tuple)):
            return True
    return False

def ZipAllElements(a, b, c):
    if CheckIfList(a):
        r = zip(a, b)
        for i in r:
            if isinstance(i[0], (list, tuple)):
                ZipAllElements(i[0], i[1], c)
            else:
                c.append(i)
    else:
        c.extend(list(zip(a, b)))

ZipAllElements(a, b, c)
print c
In [3]: from compiler.ast import flatten

In [4]: zip(flatten(A), flatten(B))
Out[4]: [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5)]