如果在另一个数组中发现重复元素,则组合数组

2024-05-29 08:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数组列表,如下所示:

[array(['A2', 'A1'], dtype=object),
 array(['A2', 'A3'], dtype=object),
 array(['A2', 'A4'], dtype=object),
 array(['A1', 'A3'], dtype=object),
 array(['A1', 'A4'], dtype=object),
 array(['A3', 'A4'], dtype=object),
 array(['B2', 'B1'], dtype=object),
 array(['B2', 'B3'], dtype=object),
 array(['B1', 'B3'], dtype=object)]

如果一个数组中的一个元素在另一个数组中找到,我想合并这些数组。然后移除复制品

预期结果应该是:

[array['A1', 'A2', 'A3', 'A4'], array[B1', 'B2', 'B3']]

你知道我该怎么做吗? 干杯


Tags: a2元素列表objecta1数组arrayb2
2条回答

听起来您需要图形的连接组件

from numpy import array

edges = [
    array(['A2', 'A1'], dtype=object),
    array(['A2', 'A3'], dtype=object),
    array(['A2', 'A4'], dtype=object),
    array(['A1', 'A3'], dtype=object),
    array(['A1', 'A4'], dtype=object),
    array(['A3', 'A4'], dtype=object),
    array(['B2', 'B1'], dtype=object),
    array(['B2', 'B3'], dtype=object),
    array(['B1', 'B3'], dtype=object),
]

import networkx
G = networkx.Graph()
G.add_edges_from(edges)
print(list(networkx.connected_components(G)))
# [{'A1', 'A3', 'A4', 'A2'}, {'B2', 'B1', 'B3'}]

演示:https://repl.it/repls/FluidPleasedScope

networkx documentation

您可以使用,^{}+^{}

from itertools import groupby
from numpy import array, unique

values = [
    array(['A2', 'A1'], dtype=object),
    array(['A2', 'A3'], dtype=object),
    array(['A2', 'A4'], dtype=object),
    array(['A1', 'A3'], dtype=object),
    array(['A1', 'A4'], dtype=object),
    array(['A3', 'A4'], dtype=object),
    array(['B2', 'B1'], dtype=object),
    array(['B2', 'B3'], dtype=object),
    array(['B1', 'B3'], dtype=object)
]

print([
    list(v) for _, v in groupby(unique(values), key=lambda x: x[0])
])

[['A1', 'A2', 'A3', 'A4'], ['B1', 'B2', 'B3']]

相关问题 更多 >

    热门问题