The pythonic way to generate pairs

前端 未结 7 1038
轮回少年
轮回少年 2020-12-30 20:00

I want something like code below, but \"pythonic\" style or using standard library:

def combinations(a,b):
    for i in a:
        for j in b:
             y         


        
7条回答
  •  误落风尘
    2020-12-30 20:36

    As @Sven said, your code is attempting to get all ordered pairs of elements of the lists a and b. In this case itertools.product(a,b) is what you want. If instead you actually want "combinations", which are all unordered pairs of distinct elements of the list a, then you want itertools.combinations(a,2).

    >>> for pair in itertools.combinations([1,2,3,4],2):
    ...    print pair
    ...
    (1, 2)
    (1, 3)
    (1, 4)
    (2, 3)
    (2, 4)
    (3, 4)
    

提交回复
热议问题