繁体   English   中英

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

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

基本上,所有你需要做的是,迭代ab同时和返回的值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函数:

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也可以正常工作。
  • 可使用yield from于python3.3 +语法( yield from recurse_zip(*t)
  • 发电机很棒。

您可以使用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)]

您可以使用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)]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM