Find duplicate items within a list of list of tuples Python

后端 未结 3 1359
醉话见心
醉话见心 2021-01-14 22:36

I want to find the matching item from the below given list.My List may be super large.

The very first item in the tuple \"N1_10\" is duplicated and matched with anot

3条回答
  •  滥情空心
    2021-01-14 23:15

    Does output order matter? This is the simplest way I could think of:

    ListA  = [[('N1_10', 'N2_28'), ('N1_35', 'N2_44')],[('N1_22', 'N3_72'), ('N1_10', 'N3_98')],
                [('N2_33', 'N3_28'), ('N2_55', 'N3_62'), ('N2_61', 'N3_37')]]
    
    idx = dict()
    
    for sublist in ListA:
        for pair in sublist:
            for item in pair:
                mapping = idx.get(item,set())
                mapping.update(pair)
                idx[item] = mapping 
                for subitem in mapping:
                    submapping = idx.get(subitem,set())
                    submapping.update(mapping)
                    idx[subitem] = submapping
    
    
    for x in set([frozenset(x) for x in idx.values()]):
        print list(x)
    

    Output:

    ['N3_72', 'N1_22']
    ['N2_28', 'N3_98', 'N1_10']
    ['N2_61', 'N3_37']
    ['N2_33', 'N3_28']
    ['N2_55', 'N3_62']
    ['N2_44', 'N1_35']
    

提交回复
热议问题