【问题标题】:Merge two lists if an element is a duplicate (python) [duplicate]如果元素是重复的,则合并两个列表(python)[重复]
【发布时间】:2015-05-25 21:28:29
【问题描述】:

我有一个列表列表,如果列表中的任何元素在两个列表中,我想将所有列表合并在一起。

例如,考虑以下列表: [[0],[1,2,3,4],[4,5,6],[6,7,8]]

输出应该是: [0],[1,2,3,4,5,6,7,8]

【问题讨论】:

  • 那么[[0],[1,2,3,4],[4,5,6],[6,7,8],[0,1,9],[6,7,8,10], [9]]的结果是什么?
  • @JonClements [0,1,2,3,4,5,6,7,8,9,10]

标签: python list merge


【解决方案1】:

试试下面的。在python3中测试。

def mergeOrNot(list1,list2):
    merge=False
    for item in list1:
        if item in list2:
            merge=True
            break
    return merge

def uniqueList(list1,list2):
    result = set()
    for item in list1:
        result.add(item)
    for item in list2:
        result.add(item)
    return result

def cleverMergeLists(lists):
    anotherLoopRequired=False
    newList = []
    for myList in lists:
        addMyList=True
        if not anotherLoopRequired:
            for myList2 in lists:
                if not anotherLoopRequired:
                    if(myList==myList2):
                        continue
                    if(mergeOrNot(myList,myList2)):
                        anotherLoopRequired=True
                        addMyList=False
                        newList.append(uniqueList(myList,myList2))
                else:
                    newList.append(myList2)
            if(addMyList):
                newList.append(myList)
    if anotherLoopRequired:
        return cleverMergeLists(newList)
    else:
        return newList


print(cleverMergeLists([[0],[1,2,3,4],[4,5,6],[6,7,8]]))

输出以下内容:

[0], {1, 2, 3, 4, 5, 6, 7, 8}] 

不能保证效率或任何东西,我只在你的列表中测试过,所以可能包含错误或在某些情况下不起作用。

cleverMergeLists 函数循环遍历列表中的项目,并确定两个项目是否需要合并。如果有,它会在合并了两个项目的新列表上调用自己,如果没有,它会返回传递给它的列表。

【讨论】:

    猜你喜欢
    • 2021-06-13
    • 2017-07-26
    • 2022-07-07
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2014-12-09
    • 2015-09-02
    • 1970-01-01
    相关资源
    最近更新 更多