【问题标题】:Duplicating and Inserting into Nested List Python复制并插入到嵌套列表 Python
【发布时间】:2017-09-08 08:33:03
【问题描述】:

我目前有嵌套列表:

A = [[a1, a2, a3], c1, [a4, a5, a6], c2]

我还有另一个清单:

B = [b1, b2]

我希望通过 B 中的元素数复制 A,然后按以下方式插入列表 B:

AB = [[a1, a2, a3], b1, c1, [a4, a5, a6], b1, c2, [a1, a2, a3], b2, c1, [a4, a5, a6], b2, c2]

我很容易找出重复的地方:

AB = A * len(B)

但是,将列表插入嵌套列表让我完全难过。

我目前使用的是 Python 3.6.1,列表 A 和 B 的大小可以更改,但格式始终为:

A template = [[x1, x2, x3], z1 ...]
B template = [y1, ...]

我们将不胜感激。

【问题讨论】:

    标签: python list nested


    【解决方案1】:

    你可以用简单的方式来做。

    A = [['a1', 'a2', 'a3'], 'c1', ['a4', 'a5', 'a6'], 'c2']
    
    AB=[]
    
    B = ['b1', 'b2']
    for i in B:
        for j in A:
            if isinstance(j,list):
                AB.append(j)
            else:
                AB.append(i)
                AB.append(j)
    print AB
    

    输出:[['a1', 'a2', 'a3'], 'b1', 'c1', ['a4', 'a5', 'a6'], 'b1', 'c2', ['a1', 'a2', 'a3'], 'b2', 'c1', ['a4', 'a5', 'a6'], 'b2', 'c2']

    【讨论】:

    • 谢谢您,思考了几个小时,您向我展示了 Python 初学者最简单的方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多