从两个嵌套列表创建元组列表 [英] Create a list of tuples from two nested lists

查看:134
本文介绍了从两个嵌套列表创建元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Having a list A with an arbitrary degree of nesting, and a list B with a nesting structure equivalent to that of A (or deeper), how can we create a list of tuples for all corresponding elements? For example:

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的当前元素不是列表.由于您的结构是嵌套的,因此我们无法进行线性迭代.这就是我们使用递归的原因.

Basically, all you need to do is, iterate a and b simultaneously and return the values of a and b, if the current element of a is not a list. Since your structure is nested, we can't lineraly iterate them. That is why we use recursion.

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

This solution assumes that there is always an corresponding element in B for every element in 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)]

这篇关于从两个嵌套列表创建元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆