Commutative combination of elements of two lists

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

    Probably the simplest and most explicit (i.e. self-explanatory) solution is this I think:

    >>> for i in range(len(a)): 
    ...     for j in range(i+1, len(b)): 
    ...         print(a[i], a[j]) 
    ... 
    1 2
    1 3
    2 3
    

    Unless you're doing something very fast in the inner loop, the inefficiency of the python for loops will hardly be a bottleneck.

    Or, this:

    >>> [(a[i], b[j]) for i in range(len(a)) for j in range(i+1, len(b))]
    [('1', '2'), ('1', '3'), ('2', '3')]
    

提交回复
热议问题