How to get all combinations of length n in python

前端 未结 3 1183
既然无缘
既然无缘 2020-11-29 10:17

I was wondering if there is any way of getting all combinations of length n from a list of numbers.

For example, if my list is [1, 2, 3, 4]

3条回答
  •  庸人自扰
    2020-11-29 10:46

    Adding the recursive function:

    def combinations(array, tuple_length, prev_array=[]):
        if len(prev_array) == tuple_length:
            return [prev_array]
        combs = []
        for i, val in enumerate(array):
            prev_array_extended = prev_array.copy()
            prev_array_extended.append(val)
            combs += combinations(array[i+1:], tuple_length, prev_array_extended)
        return combs
    
    combinations([1, 2, 3, 4], 3)
    

    Outputs:

    [[1, 2, 3], 
    [1, 2, 4], 
    [1, 3, 4], 
    [2, 3, 4]]
    

提交回复
热议问题