如果存在重复值,则合并所有子列表,同时删除所有重复项

时间:2019-07-04 20:30:46

标签: python arrays list duplicates

假设我有一个列表列表:

lists = [
    [1, 2, 5, 7],
    [3, 6, 8, 10],
    [2, 7, 9, 11]
]

如果它们具有相交的值,我想合并它们(从最低到最大的索引),同时不复制重复项,以便输出看起来像:

new_lists = [
    [1, 2, 5, 7, 9, 11],
    [3, 6, 8, 10],
]

相对有效的同时,我如何管理大量列表

2 个答案:

答案 0 :(得分:0)

尝试一下:

lists = [
    [1, 2, 5, 7],
    [3, 6, 8, 10],
    [2, 7, 9, 11]
]

newlist=[]
for sublist in lists:
    r=sublist[-1]
    i=1
    for sublist_ in lists[i:]:
        if r in sublist_:
            lists.remove(sublist_)
            sublist.extend(sublist_[sublist_.index(r)+1:])
            newlist.append(sublist)
    i=i+1
print([list(i) for i in set(map(tuple, newlist))])

输出

[[1, 2, 5, 7, 9, 11], [3, 6, 8, 10]]

答案 1 :(得分:0)

因此,这是一种与我上面的评论类似的Python 2.7方法:

lists = [
    [1, 2, 5, 7, 13],
    [3, 6, 8, 10, 13],
    [2, 7, 9, 11]
]

thedict = {}
for sublist in lists:
    for el in sublist:
        thedict[el] = 1

keylist = thedict.keys()

# at this point, you have one merged list:

print str(keylist)

# You might want to sort it, as key order is not assured

keylist.sort()

# if you want smaller lists, then you can do something like this:

listsize = 5
outlistoflists = []
for i in range(0, len(keylist), listsize):
    sublist = keylist[i:i + listsize]
    outlistoflists.append(sublist)

print str(outlistoflists)