Generating all combinations of a list in python

后端 未结 7 2149
不思量自难忘°
不思量自难忘° 2020-11-27 19:29

Here\'s the question:

Given a list of items in Python, how would I go by to get all the possible combinations of the items?

There are several similar questio

7条回答
  •  失恋的感觉
    2020-11-27 19:56

    I assume you want all possible combinations as 'sets' of values. Here is a piece of code that I wrote that might help give you an idea:

    def getAllCombinations(object_list):
        uniq_objs = set(object_list)
        combinations = []
        for obj in uniq_objs:
            for i in range(0,len(combinations)):
                combinations.append(combinations[i].union([obj]))
            combinations.append(set([obj]))
    return combinations
    

    Here is a sample:

    combinations = getAllCombinations([20,10,30])
    combinations.sort(key = lambda s: len(s))
    print combinations
    ... [set([10]), set([20]), set([30]), set([10, 20]), set([10, 30]), set([20, 30]), set([10, 20, 30])]
    

    I think this has n! time complexity, so be careful. This works but may not be most efficient

提交回复
热议问题