简体   繁体   English

如何将两个列表合并为第三个列表?

[英]How to combine two lists into a third list?

I got three list of lists:我得到了三个列表列表:

A=[[9, 'a'], [0, 'c'], [2, 'g'], [7, 'w'], [0, 'Q']]
B=[[0, 'a'], [0, 'c'], [0, 'w'], [0, 'Q'], [3, 'front'], [5, 'Z']]
C=[[9, 'a'], [0, 'c'], [7, 'w'], [0, 'Q']]

and I want to combine A and B into C like this:我想像这样将 A 和 B 组合成 C:

C=[[9, 'a'], [0, 'c'],[7, 'w'], [0, 'Q'],[2,'g'], [3,'front'],[5,'Z']] 

Basically list with g is not in C so I append into C.Same for list B.基本上带有 g 的列表不在 C 中,所以我将列表 B 附加到 C.Same 中。

EDIT:I do not need a specific index just append into C.The output is just an example output.It can be in any order.编辑:我不需要特定的索引,只需将其附加到 C 中即可。输出只是一个示例输出。它可以按任何顺序排列。

If I understood the question correctly, it sounds like you want to add to C values from A and B that were not already in it, making a set of unique values?如果我正确理解了这个问题,听起来您想将 A 和 B 中尚未包含的 C 值添加到 C 值中,从而形成一组唯一值? If so, this is the way to go:如果是这样,这是要走的路:

C = [list(x) for x in set(tuple(x) for x in A+B+C)]
from itertools import zip_longest
for x,y in zip_longest(enumerate(A),enumerate(B)):
    for i in x,y:
        if i is not None and i[1][1] not in map(lambda i: i[1], C):
            if(i[0] < len(C)):
                C.insert(i[0], i[1])
            else:
                C.append(i[1])
print(C)

In order to have the location data as you outlined, this approach seems to work.为了获得您概述的位置数据,这种方法似乎有效。 It's output is: [[3, 'front'], [5, 'Z'], [7, 'w'], [0, 'Q'], [0, 'c'], [0, 'w'], [9, 'a'], [2, 'g'], [0, 'a']]它的输出是: [[3, 'front'], [5, 'Z'], [7, 'w'], [0, 'Q'], [0, 'c'], [0, 'w '], [9, 'a'], [2, 'g'], [0, 'a']]

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

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