Get all pairwise combinations from a list

后端 未结 2 1020
刺人心
刺人心 2021-01-11 12:22

For example, if the input list is

[1, 2, 3, 4]

I want the output to be

[[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 13:08

    import itertools
    
    x = [1,2,3,4]
    
    for each in itertools.permutations(x,2):
        print(each)
    

    Note that itertools is a generator object, meaning you need to iterate through it to get all you want. The '2' is optional, but it tells the function what's the number per combination you want.

    You can read more here

    Edited:

    As ForceBru said in the comment, you can unpack the generator to print, skipping the for loop together But I would still iterate through it as you might not know how big the generated object will be:

    print(*itertools.permutations(x, 2))
    

提交回复
热议问题