intersection of tuples in a list - python

后端 未结 3 1059
耶瑟儿~
耶瑟儿~ 2020-12-21 08:35

I have a list of tuples like this :

all_tuples=[(92, 242),(355, 403),(355, 436),(355, 489),(403, 436),(436, 489),(515, 517),(517, 859),(634, 775),(701, 859)         


        
3条回答
  •  半阙折子戏
    2020-12-21 08:55

    This solution builds a list of equivalence classes, where being in the same tuple is our equivalence relation. For each tuple, we make a list of all the sets in our list that match some element of that tuple. If there is none, we make a set of that tuple and add it to the list. If there is one, we update that set to include the other items of the tuple. If there are multiple, we remove them from the list, combine them and the tuple unto one set, then add that set to the list.

    res = []
    for t in all_tuples:
        matched = []
        for s in res:
            if s.intersection(t):
                matched.append(s)
        if not matched:
            res.append(set(t))
        elif len(matched) == 1:
            matched[0].update(t)
        else:
            res = [subl for subl in res if subl not in matched]
            res.append(set.union(*matched, t))
    
    print(res)
    # [{242, 92}, {489, 436, 355, 403}, {515, 517, 775, 634, 859, 701}]
    

提交回复
热议问题