嵌套列表,检查一个列表是否与其他列表具有共同元素,如果是这样,则加入

时间:2015-03-04 09:12:16

标签: python list python-2.7

我的列表中有一个列表[[1, 3, 5], [2, 4], [1,7,9]]

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

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

我该怎么办?

3 个答案:

答案 0 :(得分:1)

ALGO:

  1. 从新方法中获取基本元素。
  2. 从输入列表中删除第一项并为其创建新变量。
  3. 对新列表中的每个项目进行迭代。
  4. 通过设置intersection方法检查基本集中是否存在项目中的任何元素。
  5. 如果存在则执行6,7,8,9
  6. 按照update方法设置当前项目更新基础。
  7. 从列表中删除当前项目。
  8. 将标记设置为True
  9. 打破for循环,因为需要再次检查第一项。
  10. 创建最终结果列表添加添加基础和剩余列表。
  11. <强> [编辑:]

    <强>问题:

    以前的代码将基本项目视为给定列表中的第一项,但是当该项目与其他项目没有匹配且其他项目具有匹配时,则代码将无效。

    已更新:

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

    <强> [EDIT2]:

    将合并项目插入相应位置

    演示:

    import copy
    
    a = [[13, 15, 17], [66,77], [1, 2, 4], [1,7,9]]
    
    #- Get base
    base = None
    length_a = len(a)
    base_flag = True
    i = -1
    while base_flag and i!=length_a-1:
        i += 1
        item = a[i]
        for j in xrange(i+1, length_a):
            tmp = set(item).intersection(set(a[j]))
            if tmp:
                base = set(item)
                base_flag = False
                break
    
    print "Selected base:", base
    if base:
        tmp_list = copy.copy(a)
        target_index = i
        tmp_list.pop(target_index)
        flag = True
        while flag:
            flag = False
            for i, item in enumerate(tmp_list):
                tmp = base.intersection(set(item))
                if tmp:
                    base.update(set(item))
                    tmp_list.pop(i)
                    flag = True
                    break
    
        print "base:", base
        print "tmp_list:", tmp_list
        result = tmp_list
        result.insert(target_index, list(base))
    
    else:
        result = a
    
    print "\nFinal result:", result
    

    输出:

    $ 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 :(得分:0)

效率很低,但这样做很有效:

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

答案 2 :(得分:0)

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