Commutative combination of elements of two lists

前端 未结 6 568
感动是毒
感动是毒 2021-01-15 14:13

Just a style question: Is there a build-in method to get the combinations under the assertion of commutative property and excluding elements paired with itself?



        
6条回答
  •  清歌不尽
    2021-01-15 14:33

    itertools.combinations, if both lists are the same like here. Or in the general case itertools.product, followed by some filtering:

    In [7]: a = ["1", "2", "3"]
       ...: b = ["a", "b", "c"]
    
    In [8]: list(filter(lambda t: t[0] < t[1], product(a,b)))
    Out[8]: 
    [('1', 'a'),
     ('1', 'b'),
     ('1', 'c'),
     ('2', 'a'),
     ('2', 'b'),
     ('2', 'c'),
     ('3', 'a'),
     ('3', 'b'),
     ('3', 'c')]
    

    Also, I think the term combination already means that the order of elements in the result doesn't matter.


    Ok, Theodros is right. For compensation, here's a version which should work on a any list of lists:

    l = [['1','2','3'], ['a','b'], ['x','y']] 
    
    set(tuple(sorted(p)) for p in product(*l) if len(set(p)) > 1)
    

    gives (appropriately sorted)

    set([('1', 'a', 'x'),
         ('3', 'a', 'y'),
         ('2', 'b', 'y'),
         ('2', 'a', 'y'),
         ('1', 'a', 'y'),
         ('1', 'b', 'y'),
         ('2', 'a', 'x'),
         ('3', 'b', 'y'),
         ('1', 'b', 'x'),
         ('2', 'b', 'x'),
         ('3', 'a', 'x'),
         ('3', 'b', 'x')])
    

    And it also works on the previous counterexample l = [[1,2,3], [1,3,4,5]]:

    set([(1, 2), (1, 3), (1, 4), (1, 5), (2, 3), (2, 5), (3, 4), (2, 4), (3, 5)])
    

提交回复
热议问题