gpt4 book ai didi

python - 如何根据共享项目有效地分组对?

转载 作者:太空狗 更新时间:2023-10-30 02:07:05 25 4
gpt4 key购买 nike

我有一个对(元组)的列表,为了简化是这样的:

L = [("A","B"), ("B","C"), ("C","D"), ("E","F"), ("G","H"), ("H","I"), ("G","I"), ("G","J")]

我想使用 python 有效地将此列表拆分为:

L1 = [("A","B"), ("B","C"), ("C","D")]
L2 = [("E","F")]
L3 = [("G","H"), ("G","I"), ("G","J"), ("H","I")]

如何有效地将列表分成成对的组,对于组中的成对,必须始终至少有一对与其他人共享一个项目?如其中一个答案所述,这是实际上是网络问题。目标是有效地将网络拆分为断开(隔离)的网络部分。

类型列表、元组(集合)可能会改变以实现更高的效率。

最佳答案

这更像是一个网络问题,所以我们可以使用networkx:

import networkx as nx
G=nx.from_edgelist(L)

l=list(nx.connected_components(G))
# after that we create the map dict , for get the unique id for each nodes
mapdict={z:x for x, y in enumerate(l) for z in y }
# then append the id back to original data for groupby
newlist=[ x+(mapdict[x[0]],)for x in L]
import itertools
#using groupby make the same id into one sublist
newlist=sorted(newlist,key=lambda x : x[2])
yourlist=[list(y) for x , y in itertools.groupby(newlist,key=lambda x : x[2])]
yourlist
[[('A', 'B', 0), ('B', 'C', 0), ('C', 'D', 0)], [('E', 'F', 1)], [('G', 'H', 2), ('H', 'I', 2), ('G', 'I', 2), ('G', 'J', 2)]]

然后匹配你的输出格式:

L1,L2,L3=[[y[:2]for y in x] for x in yourlist]
L1
[('A', 'B'), ('B', 'C'), ('C', 'D')]
L2
[('E', 'F')]
L3
[('G', 'H'), ('H', 'I'), ('G', 'I'), ('G', 'J')]

关于python - 如何根据共享项目有效地分组对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55232459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com