Skip to main content
 首页 » 编程设计

python之如何使用 python 中的一组标签生成标记(分类)一组对象的所有可能方式

2024年11月24日8mfrbuaa

假设我们有一组对象:

set_of_objects = {1, 2, 3, 4, 5} 

和一组类:

set_of_classes = {'a', 'b', 'c'} 

我们如何生成将对象集合分类为 python 类集合中所有可能类的所有方法?

示例输出如下:

[[1],[2],[3]] 
[[1,2],[3],[]] 
[[1,2,3],[],[]] 
[[3],[2],[1]] 
and so on... 

我们可以将 n 个对象分为 k 类的所有方法的数量是:k ^ n,因为我们可以将 n 个对象中的每一个都分配到 k 类中。

请您参考如下方法:

您可以使用递归算法来生成分区:

import itertools 
 
def part(lst, n): 
    if n <= 1: 
        # single answer for 1 partition 
        yield [lst] 
    else: 
        for m in range(len(lst)+1): 
            for head in itertools.combinations(lst, m): 
                nothead = [x for x in lst if x not in head] 
                for tail in part(nothead, n-1): 
                    yield [list(head)]+tail 
 
def partition(n): 
    lst = list(range(n)) 
    for x in part(lst, n): 
        print(x) 

示例:分区(3):

[[], [], [0, 1, 2]] 
[[], [0], [1, 2]] 
[[], [1], [0, 2]] 
[[], [2], [0, 1]] 
[[], [0, 1], [2]] 
[[], [0, 2], [1]] 
[[], [1, 2], [0]] 
[[], [0, 1, 2], []] 
[[0], [], [1, 2]] 
[[0], [1], [2]] 
[[0], [2], [1]] 
[[0], [1, 2], []] 
[[1], [], [0, 2]] 
[[1], [0], [2]] 
[[1], [2], [0]] 
[[1], [0, 2], []] 
[[2], [], [0, 1]] 
[[2], [0], [1]] 
[[2], [1], [0]] 
[[2], [0, 1], []] 
[[0, 1], [], [2]] 
[[0, 1], [2], []] 
[[0, 2], [], [1]] 
[[0, 2], [1], []] 
[[1, 2], [], [0]] 
[[1, 2], [0], []] 
[[0, 1, 2], [], []]