목록 요소 합성 파이썬 두 개 이상의 중복 된 목록

파이썬로리스트 데이터 구조는 두 경우 이상의 동일한 목록 구조에 사용되는 동일한 컨텐츠 유형, 우리는 일반적으로 두 개 이상의 경우 이송 우리가 재활용 될 수 있도록리스트로 병용 속성은 폐기. 하나는 우리가 말하고 싶은 것입니다 옆 그래서 두 개 이상의 목록에 병합하는 방법.

예 효과 :

[1,2], [3,4,5], [0,4]가된다 [1,2], [0,3,4,5]

[1], [1,2]은 [0,2]가된다 [0,1,2]

[1,2], [2,3], [3,4]가된다 [1,2,3,4]

1 itertools 달성

from itertools import combinations

def bfs(graph, start):
    visited, queue = set(), [start]
    while queue:
        vertex = queue.pop(0)
        if vertex not in visited:
            visited.add(vertex)
            queue.extend(graph[vertex] - visited)
    return visited

def connected_components(G):
    seen = set()
    for v in G:
        if v not in seen:
            c = set(bfs(G, v))
            yield c
            seen.update(c)

def graph(edge_list):
    result = {}
    for source, target in edge_list:
        result.setdefault(source, set()).add(target)
        result.setdefault(target, set()).add(source)
    return result

def concat(l):
    edges = []
    s = list(map(set, l))
    for i, j in combinations(range(len(s)), r=2):
        if s[i].intersection(s[j]):
            edges.append((i, j))
    G = graph(edges)
    result = []
    unassigned = list(range(len(s)))
    for component in connected_components(G):
        union = set().union(*(s[i] for i in component))
        result.append(sorted(union))
        unassigned = [i for i in unassigned if i not in component]
    result.extend(map(sorted, (s[i] for i in unassigned)))
    return result

print(concat([[1, 2], [3, 4, 5], [0, 4]]))
print(concat([[1], [1, 2], [0, 2]]))
print(concat([[1, 2], [2, 3], [3, 4]]))

출력 :
[0, 3, 4, 5], [1, 2]
[0, 1, 2]
[1, 2, 3, 4]

목록 요소 합성 파이썬 두 개 이상의 중복 된 목록

2 반복 방법은 달성

original_list = [[1,2],[3,4,5],[0,4]]
mapping = {}
rev_mapping = {}
for i, candidate in enumerate(original_list):
    sentinel = -1
    for item in candidate:
        if mapping.get(item, -1) != -1:
            merge_pos = mapping[item]
            #update previous list with all new candidates
            for item in candidate:
                mapping[item] = merge_pos
            rev_mapping[merge_pos].extend(candidate)
            break
    else:
        for item in candidate:
            mapping[item] = i
        rev_mapping.setdefault(i, []).extend(candidate)
result = [list(set(item)) for item in rev_mapping.values()]
print(result)

출력 :
[1, 2], [0, 3, 4, 5]

목록 요소 합성 파이썬 두 개 이상의 중복 된 목록

추천

출처www.linuxidc.com/Linux/2020-02/162381.htm