Python 如何将基于公共值的元组列表合并到一个列表中
我有一个很长的元组列表,可以如下所示,例如:Python 如何将基于公共值的元组列表合并到一个列表中,python,list,tuples,Python,List,Tuples,我有一个很长的元组列表,可以如下所示,例如: [('5','9'), ('10','11'), ('1','2'), ('1','3'), ('1','4'), ('2','7'), ('3','8'), ('2','1'), ('3','1'), ('3','4'), ('5','6'), ('5','10'), ('10','12'), ('11','13'), ('13','14')] 如果它们有共同之处,我需要将它们合并到列表中。因此,示例中的输出为: ['11', '10', '
[('5','9'), ('10','11'), ('1','2'), ('1','3'), ('1','4'), ('2','7'), ('3','8'), ('2','1'), ('3','1'), ('3','4'), ('5','6'), ('5','10'), ('10','12'), ('11','13'), ('13','14')]
如果它们有共同之处,我需要将它们合并到列表中。因此,示例中的输出为:
['11', '10', '13', '12', '14', '5', '6', '9']
['1', '3', '2', '4', '7', '8']
澄清:输入是一个元组列表。我需要将所有具有共享元素的元组组合到一个列表中。所以如果我有:[('1','2'),('1','3'),('1','4'),('4','5')],所有元素都应该放在一个列表['1','2','3','4','5')],因为它们是通过元组链接的
我试图通过字典找出一些东西,但不幸失败了。我相信有一些“更简单”的解决办法
多谢各位
Martin看起来您正在执行联合查找操作 从创建单例不相交集开始,每个集合的列表中都有一个数字。接下来,对于每个元组,将与元组中的数字对应的集合合并
上述解决方案的运行时间在元组数量上几乎是线性的。请参阅以了解可能的联合查找实现。我们可以将此问题定义为在无向图中查找连接组件的问题。列表中出现的所有不同数字都可以视为图形的节点(顶点),而对则可以视为其边 下面是一个带有内联注释的简单算法:
l = [('5','9'), ('10','11'), ('1','2'), ('1','3'), ('1','4'), ('2','7'), ('3','8'), ('2','1'), ('3','1'), ('3','4'), ('5','6'), ('5','10'), ('10','12'), ('11','13'), ('13','14')]
# get all unique elements ("nodes") of `l'
nodes = set().union(*map(set, l))
# start with each node in its own connected component
comp = {node:{node} for node in nodes}
# now repeatedly merge pairs of components connected by edges in `l'
while True:
merged = False
new_l = [] # will drop edges that have already been used in a merge
for n1, n2 in l:
if comp[n1] is not comp[n2]:
# the two connected components are not the same, so merge them
new_comp = comp[n1] | comp[n2]
for n in new_comp:
comp[n] = new_comp
merged = True
else:
# keep the pair for the next iteration
new_l.append((n1, n2))
if not merged:
# all done
break
l = new_l
# now print all distinct connected components
for c in set(map(frozenset, comp.values())):
print list(c)
这将打印出:
['1', '3', '2', '4', '7', '8']
['11', '10', '13', '12', '14', '5', '6', '9']
你用的是什么语言?我应该补充一点,我用的是python,我已经添加了python标记。如果你不添加语言标签,几乎没有人会看到你的问题。你能澄清什么是共享共同的意思吗?@PaulBoddington:所以输入是一个元组列表。我需要将所有具有共享元素的元组组合到一个列表中。所以如果我有:[('1','2'),('1','3'),('1','4'),('4','5')],所有元素都应该放在一个列表中['1','2','3','4','5',],因为它们是通过元组链接的。非常感谢。在你发布的链接中找到一个有效的代码!