将具有相同值的元组合并到列表中 [英] Combine tuples in a list which have the same value
问题描述
我有一个包含这样的元组的列表:
I have a list with tuples like this:
L ={(1,2), (1,4), (1,3), (2,3), (3,4), (3,5), (4,5), (6,7)}
我尝试将它们合并以获得等价类(合并相同值的元组,如(1,2)和(2,3)变为(1,2,3)).这样您就会得到:
I try to combine these to get equivalence classes (tuples of the same value are merged, like (1,2) and (2,3) becomes (1,2,3)). So you get:
EQ = {(1,2,3,4,5), (6,7)}
在Python中最简单的方法是什么?
What's the easiest way to accomplish this in Python?
推荐答案
您可以使用以下递归函数.首先,您可以将元素转换为set
并通过set并检查if之后的任何元素,当找到具有任何交集(v & k
)的元素时,将这些集合合并在一起并从中删除第二个元素列出并更新主列表:
You can use the following recursion function . first you can convert the elements to set
and go though the set and check any element with the elements after if , when you find an element that have any intersection (v & k
) you merg thous set together and remove the second element from list and update the main list :
L ={(1,2), (1,4), (1,3), (2,3), (3,4), (3,5), (4,5), (6,7)}
s=[set(i) for i in L if i]
def find_intersection(m_list):
for i,v in enumerate(m_list) :
for j,k in enumerate(m_list[i+1:],i+1):
if v & k:
s[i]=v.union(m_list.pop(j))
return find_intersection(m_list)
return m_list
print find_intersection(s)
结果:
[set([1, 2, 3, 4, 5]), set([6, 7])]
[Finished in 0.0s]
请注意,在第二个enumerate
函数中,我将i + 1用作索引m_list[i+1:]
的起始编号,因为k(j)的索引等于主列表中k的索引.
Note that in the second enumerate
function i use i+1 for the start number for indexing of m_list[i+1:]
because of that the index of k (j) be equal with the index of k in main list.
这篇关于将具有相同值的元组合并到列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!