Commutative combination of elements of two lists

前端 未结 6 515
感动是毒
感动是毒 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:39

    This will work if you do not care that the ordering in the resulting tuples does not map to the input lists (you do not care whether (1,2) or (2,1)). Here you'll get the combination with the smaller element first:

    a = [1,2,3]
    b = [1,3,4,5]
    
    set([(min(x,y), max(x,y)) for x in a for y in b if x != y])
    

    gives

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

    With strings

    a = '1 2 3'.split()
    b = '1 3 4 5'.split()
    

    you get

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

    The apparent difference in the ordering comes from the different hashes for the strings and the numbers.

提交回复
热议问题