Better to add item to a set, or convert final list to a set?

后端 未结 4 2111
北海茫月
北海茫月 2021-02-20 16:47

I have some data that looks something like this:

ID1 ID2 ID3  
ID1 ID4 ID5  
ID3 ID5 ID7 ID6  
...  
...  

where each row is a group.

M

4条回答
  •  庸人自扰
    2021-02-20 17:24

    Option 2 sounds the most logical to me, especially with a defaultdict it should be fairly easy to do :)

    import pprint
    import collections
    
    data = '''ID1 ID2 ID3
    ID1 ID4 ID5
    ID3 ID5 ID7 ID6'''
    
    groups = collections.defaultdict(set)
    
    for row in data.split('\n'):
        cols = row.split()
        for groupcol in cols:
            for col in cols:
                if col is not groupcol:
                    groups[groupcol].add(col)
    
    pprint.pprint(dict(groups))
    

    Results:

    {'ID1': set(['ID2', 'ID3', 'ID4', 'ID5']),
     'ID2': set(['ID1', 'ID3']),
     'ID3': set(['ID1', 'ID2', 'ID5', 'ID6', 'ID7']),
     'ID4': set(['ID1', 'ID5']),
     'ID5': set(['ID1', 'ID3', 'ID4', 'ID6', 'ID7']),
     'ID6': set(['ID3', 'ID5', 'ID7']),
     'ID7': set(['ID3', 'ID5', 'ID6'])}
    

提交回复
热议问题