Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 嵌套列表,检查一个列表是否与另一个列表具有公共元素,如果是,则连接_Python_List_Python 2.7 - Fatal编程技术网

Python 嵌套列表,检查一个列表是否与另一个列表具有公共元素,如果是,则连接

Python 嵌套列表,检查一个列表是否与另一个列表具有公共元素,如果是,则连接,python,list,python-2.7,Python,List,Python 2.7,我在列表中有一个列表,上面写着[[1,3,5],[2,4],[1,7,9] 我的要求是我想遍历列表并将其缩减为 [[1,3,5,7,9],[2,4]] 我该怎么做呢?效率很低,但这确实起到了关键作用: def combine_lists(lists): # Keep a set of processed items skip = set() for i, a in enumerate(lists): # If we already used this l

我在列表中有一个列表,上面写着
[[1,3,5],[2,4],[1,7,9]

我的要求是我想遍历列表并将其缩减为

[[1,3,5,7,9],[2,4]]


我该怎么做呢?

效率很低,但这确实起到了关键作用:

def combine_lists(lists):
    # Keep a set of processed items
    skip = set()

    for i, a in enumerate(lists):
        # If we already used this list, skip it
        if i in skip:
            continue

        for j, b in enumerate(lists[i + 1:], i + 1):
            # Use a set to check if there are common numbers
            if set(a) & set(b):
                skip.add(j)

                for x in b:
                    if x not in a:
                        a.append(x)

    # yield all lists that were not added to different lists
    for i, a in enumerate(lists):
        if i not in skip:
            yield a
[edit]刚刚注意到顺序不再重要(您的输出表明它确实重要),这让事情变得更简单:)

这个版本应该是相当理想的:

def combine_lists(lists):
    # Keep a set of processed items
    skip = set()
    sets = map(set, lists)

    for i, a in enumerate(sets):
        # If we already returned this set, skip it
        if i in skip:
            continue

        for j, b in enumerate(sets[i + 1:], i + 1):
            # Use a set to check if there are common numbers
            if a & b:
                skip.add(j)
                a |= b

    # yield all sets that were not added to different sets
    for i, a in enumerate(sets):
        if i not in skip:
            yield a
算法:

  • 从新方法中获取基本元素
  • 从输入列表中删除第一项并为此创建新变量
  • 迭代新列表中的每个项目
  • 通过set
    intersection
    方法检查项目中的任何元素是否存在于基本集合中
  • 如果存在,则执行6,7,8,9
  • 通过set
    Update
    方法使用当前项更新基础
  • 从列表中删除当前项
  • 将标志设置为
    True
  • 中断
    for
    循环,因为需要从第一项开始再次检查
  • 创建最终结果列表添加添加基础和剩余列表
  • [编辑:

    问题:

    以前的代码将基本项视为给定列表中的第一项,但当此项与其他项不匹配且其他项具有匹配时,代码将不起作用

    更新:

    从给定列表中获取与列表中任何一项匹配的基本项

    [Edit2]:

    将合并项插入到相应位置

    演示:

    输出:

    $ python task4.py 
    Selected base: set([1, 2, 4])
    base: set([1, 2, 4, 7, 9])
    tmp_list: [[13, 15, 17], [66, 77]]
    
    Final result: [[13, 15, 17], [66, 77], [1, 2, 4, 7, 9]]
    

    减少这一比例的标准是什么?奇数和偶数?为什么要合并列表1和列表3?仅仅因为他们共享元素
    1
    ?@tim是的,如果他们有共同的元素,我想合并它们,你可以给出不止一个例子吗@DeadjangdJoker:这个
    [[1,2],[3,4],[1,5,3],[5]].
    的输出是什么?工作正常:)…谢谢:)请注意,这是如何得到4次投票和一个接受(@deadjangdJoker),这不起作用:。还要注意的是,大多数集合方法,如交集、更新等,对于任何iterable都可以正常工作,因此不需要转换为集合。@AshwiniChaudhary:是的,正确。我会在一段时间内更新。@AshwiniChaudhary:现在检查。更新并让我知道是否有更多改进,或者是否对其他测试用例不起作用?@deadjangdjoker:根据Ashwini的评论,现在检查一下。尝试过这个…力似乎对我起作用:(…谢谢aneways:)第一个解决方案似乎很好,但第二个不起作用:@AshwiniChaudhary:oops。。。似乎我在复制时出错了,最后一个
    列表应该是
    集合
    。谢谢你的提醒:)
    $ python task4.py 
    Selected base: set([1, 2, 4])
    base: set([1, 2, 4, 7, 9])
    tmp_list: [[13, 15, 17], [66, 77]]
    
    Final result: [[13, 15, 17], [66, 77], [1, 2, 4, 7, 9]]
    
    a = [[1,2], [3,4 ], [1,5,3], [5]] # output: [set([1, 2, 3, 4, 5])]
    # a = [[1, 3, 5], [2, 4], [1,7,9]] # output: [set([1, 3, 5, 7, 9]), set([2, 4])]
    
    # convert them to sets
    a = [set(x) for x in a]
    go = True
    
    while go:
        merged = False
        head = a[0]
    
        for idx, item in enumerate(a[1:]):
            if head.intersection(item):
                a[0] = head.union(item)
                a.pop(idx + 1)
                merged = True
                break
    
        if not merged:
            go = False
    
    print a