Python 中的排列和组合

元素组合的变异和组合是组合元素的不同安排。

  • ** 组合 ** 是元素的集合,其中命令无关紧要
  • ** 变动 ** 是命令无关紧要的集合的安排。

让我们把一套作为:

1{A, B, C}

上述集合的变异如下:

1('A', 'B', 'C')
2('A', 'C', 'B')
3('B', 'A', 'C')
4('B', 'C', 'A')
5('C', 'A', 'B')
6('C', 'B', 'A')

上述组合的组合,当两个元素结合时是:

1('A', 'B')
2('A', 'C')
3('B', 'C')

在本教程中,我们将学习如何在Python中获得元素组的转换和组合,我们将看看字符和数字的集合。

我们将在Python模块中的 **itertools**中使用 **combinations() 和 **permutations() 方法。

让我们开始吧。

数字数据的可变性

要在 itertools 模块中使用 **permutations() 方法,我们首先需要导入该模块。

1import itertools

现在让我们定义一组数字。

1val = [1, 2, 3, 4]

现在也得到 permutations 列表,让我们使用 permutations() 方法。

1perm_set = itertools.permutations(val)

上面的代码行给了一个 ittools 对象. 要打印不同的转换,我们将重复这个对象。

1for i in perm_set:
2    print(i)

我们将输出作为:

 11 2 3 4
 21 2 4 3
 31 3 2 4
 41 3 4 2
 51 4 2 3
 61 4 3 2
 72 1 3 4
 82 1 4 3
 92 3 1 4
102 3 4 1
112 4 1 3
122 4 3 1
133 1 2 4
143 1 4 2
153 2 1 4
163 2 4 1
173 4 1 2
183 4 2 1
194 1 2 3
204 1 3 2
214 2 1 3
224 2 3 1
234 3 1 2
244 3 2 1

此部分的完整代码如下:

1import itertools
2
3val = [1, 2, 3, 4]
4
5perm_set = itertools.permutations(val)
6
7for i in perm_set:
8    print(i)

一个字符串的可变性

接下来,我们将学习如何在字符串中获得字符变异。

我们将使用 permutations() 方法,但这次我们将通过一个字符串作为一个参数。

1import itertools
2
3s = "ABC"
4
5perm_set = itertools.permutations(s)
6for val in perm_set:
7    print(val)

输出:

1('A', 'B', 'C')
2('A', 'C', 'B')
3('B', 'A', 'C')
4('B', 'C', 'A')
5('C', 'A', 'B')
6('C', 'B', 'A')

固定长度的可变性

我们可以找到一个集的转换,在每个转换中,我们只采取一定数量的元素,这在数学领域类似于 nPr

查找固定长度变异的代码是以下的:

1import itertools
2
3val = [1, 2, 3, 4]
4
5perm_set = itertools.permutations(val,2)
6
7for i in perm_set:
8    print(i)

输出:

 1(1, 2)
 2(1, 3)
 3(1, 4)
 4(2, 1)
 5(2, 3)
 6(2, 4)
 7(3, 1)
 8(3, 2)
 9(3, 4)
10(4, 1)
11(4, 2)
12(4, 3)

数字数据的组合

就像方法变异(),我们可以使用组合(),也可以在 ittools 中获取集合的组合。

在调用组合() 时,我们需要传递两个参数,即找到组合的集合和一个表示每个组合的长度的数字。

1import itertools
2
3val = [1, 2, 3, 4]
4
5com_set = itertools.combinations(val, 2)
6
7for i in com_set:
8    print(i)

输出:

1(1, 2)
2(1, 3)
3(1, 4)
4(2, 3)
5(2, 4)
6(3, 4)

一个弦的组合

我们还可以获得字符串的组合. 要获得字符串的组合,请使用以下代码:

1import itertools
2
3s = "ABC"
4
5com_set = itertools.combinations(s, 2)
6
7for i in com_set:
8    print(i)

输出:

1('A', 'B')
2('A', 'C')
3('B', 'C')

与替代品的组合

在 itertools 模块中有另一种方法,称为 combinations_with_replacement()。

让我们看看它是如何工作的。

數字集合

1import itertools
2
3val = [1, 2, 3, 4]
4
5com_set = itertools.combinations_with_replacement(val, 2)
6
7for i in com_set:
8    print(i)

输出:

 1(1, 1)
 2(1, 2)
 3(1, 3)
 4(1, 4)
 5(2, 2)
 6(2, 3)
 7(2, 4)
 8(3, 3)
 9(3, 4)
10(4, 4)

您可以看到上述输出和正常组合操作的输出之间的差异. 在这里,我们有类似的组合(1,1)和(2,2)在正常组合操作中不存在。

对于一个 string

1import itertools
2
3val = "ABCD"
4
5com_set = itertools.combinations_with_replacement(val, 2)
6
7for i in com_set:
8    print(i)

输出:

 1('A', 'A')
 2('A', 'B')
 3('A', 'C')
 4('A', 'D')
 5('B', 'B')
 6('B', 'C')
 7('B', 'D')
 8('C', 'C')
 9('C', 'D')
10('D', 'D')

结论

本教程是关于在 python 中找到一个集合的转换和组合,我们使用 itertools 模块在 python 中找到转换和组合。

Published At
Categories with 技术
Tagged with
comments powered by Disqus