Pair combinations of elements in dictionary without repetition

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

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

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


        
2条回答
  •  闹比i
    闹比i (楼主)
    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']}]
    

提交回复
热议问题