📜  获取列表 python 的所有子集(1)

📅  最后修改于: 2023-12-03 15:41:27.538000             🧑  作者: Mango

获取列表 Python 的所有子集

在 Python 中,可以使用 itertools 模块中的 combinations 和 permutations 方法来获取列表的所有子集。

combinations方法

combinations 方法使用一个列表和一个整数 n 作为参数。它返回由列表中 n 个元素的所有组合构成的迭代器。

from itertools import combinations

lst = [1, 2, 3]
 
for i in range(len(lst)+1):
    for subset in combinations(lst, i):
        print(subset)

输出结果:

()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 3)
(1, 2, 3)

以上代码中,我们取出长度为 0、1、2 和 3 的所有组合并打印出来。

permutations方法

permutations 方法使用一个列表和一个整数 n 作为参数。它返回由列表中 n 个元素的所有排列构成的迭代器。

from itertools import permutations

lst = [1, 2, 3]
 
for i in range(len(lst)+1):
    for subset in permutations(lst, i):
        print(subset)

输出结果:

()
(1,)
(2,)
(3,)
(1, 2)
(1, 3)
(2, 1)
(2, 3)
(3, 1)
(3, 2)
(1, 2, 3)
(1, 3, 2)
(2, 1, 3)
(2, 3, 1)
(3, 1, 2)
(3, 2, 1)

以上代码中,我们取出长度为 0、1、2 和 3 的所有排列并打印出来。

使用以上两种方法,我们可以方便地获取列表的所有子集。