Pair combinations of elements in dictionary without repetition

后端 未结 2 685
失恋的感觉
失恋的感觉 2021-01-23 07:51

In python, I have a dictionary like this...

pleio = {\'firstLine\': {\'enf1\': [\'54\', \'set\'], 
                      \'enf2\': [\'48\', \'free\'], 
                  


        
相关标签:
2条回答
  • 2021-01-23 08:25

    Your combinations approach was correct, you just need to turn the results of each combination into a dict again:

    import itertools
    
    def pairwise(input):
        for values in input.itervalues():
            for pair in itertools.combinations(values.iteritems(), 2):
                yield dict(pair)
    

    This version is a generator, yielding pairs efficiently, nothing is held in memory any longer than absolutely necessary. If you need a list, just call list() on the generator:

    list(pairwise(pleio))
    

    Output:

    >>> from pprint import pprint
    >>> pprint(list(pairwise(pleio)))
    [{'enf2': ['48', 'free'], 'enf3': ['34', 'set']},
     {'enf1': ['54', 'set'], 'enf3': ['34', 'set']},
     {'enf3': ['34', 'set'], 'enf4': ['12', 'free']},
     {'enf1': ['54', 'set'], 'enf2': ['48', 'free']},
     {'enf2': ['48', 'free'], 'enf4': ['12', 'free']},
     {'enf1': ['54', 'set'], 'enf4': ['12', 'free']}]
    

    You can even combine the whole thing into a one-liner generator:

    from itertools import combinations
    
    for paired in (dict(p) for v in pleio.itervalues() for p in combinations(v.iteritems(), 2)):
        print paired
    

    Which outputs:

    >>> for paired in (dict(p) for v in pleio.itervalues() for p in combinations(v.iteritems(), 2)):
    ...     print paired
    ... 
    {'enf3': ['34', 'set'], 'enf2': ['48', 'free']}
    {'enf3': ['34', 'set'], 'enf1': ['54', 'set']}
    {'enf3': ['34', 'set'], 'enf4': ['12', 'free']}
    {'enf2': ['48', 'free'], 'enf1': ['54', 'set']}
    {'enf2': ['48', 'free'], 'enf4': ['12', 'free']}
    {'enf1': ['54', 'set'], 'enf4': ['12', 'free']}
    

    If you are on Python 3, replace .itervalues() and .iteritems() by .values() and .items() respectively.

    0 讨论(0)
  • 2021-01-23 08:40

    If you want all pair combinations, you could probably use the following which is shorter, but I would not say this is more efficient.

    [dict([(x,vx),(y,vy)]) for (x,vx) in pleio['firstLine'].iteritems()
                           for (y,vy) in pleio['firstLine'].iteritems()
                           if x < y]
    

    Output

    [{'enf3': ['34', 'set'], 'enf4': ['12', 'free']},
     {'enf2': ['48', 'free'], 'enf3': ['34', 'set']},
     {'enf2': ['48', 'free'], 'enf4': ['12', 'free']},
     {'enf1': ['54', 'set'], 'enf3': ['34', 'set']},
     {'enf1': ['54', 'set'], 'enf2': ['48', 'free']},
     {'enf1': ['54', 'set'], 'enf4': ['12', 'free']}]
    
    0 讨论(0)
提交回复
热议问题