在数学中,将集合的所有成员按某种顺序或序列排列,如果该集合已被排序,则重新排列(重新排列)其元素称为置换。我们可以使用不同的技术来生成排列。以下是其中一些
Python带有专用于排列和组合的模块,称为itertools。
>>> import itertools >>>
排列功能使我们能够在顺序重要的列表中获取N个值的排列。例如,选择N = 2个具有[1,2,3,4]的值,如下所示-
Permutation (order matters): >>> print(list(itertools.permutations([1,2,3,4],2))) [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
>>> print(list(itertools.combinations('1234', 2))) [('1', '2'), ('1', '3'), ('1', '4'), ('2', '3'), ('2', '4'), ('3', '4')]
下面是在列表上的实现,没有创建新的中间列表。
def permute(xs, low=0): if low + 1 >= len(xs): yield xs else: for p in permute(xs, low + 1): yield p for i in range(low + 1, len(xs)): xs[low], xs[i] = xs[i], xs[low] for p in permute(xs, low + 1): yield p xs[low], xs[i] = xs[i], xs[low] for p in permute([1, 2, 3]): print (p)
[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2]
import copy def perm(prefix,rest): for e in rest: new_rest=copy.copy(rest) new_prefix=copy.copy(prefix) new_prefix.append(e) new_rest.remove(e) if len(new_rest) == 0: print (new_prefix + new_rest) continue perm(new_prefix,new_rest) perm([],[1, 2, 3])
[1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1]