Python itertools排列如何包含重复字符

时间:2012-12-22 21:51:49

标签: python permutation itertools

  

可能重复:
  Power set and Cartesian Product of a set python

使用Python Itertools.permutations()我希望接收和输出具有重复字符的排列。举个例子,我的下面的函数及其当前输出。

def perm(n,i):
    b = 0
    while b < n:
        n= n -1
        from itertools import permutations as p
        file.write('\n'.join([''.join(item) for item in p(i,n)]))
perm(4,'0123')

输出是:

012
013
021
023
031
032
102
103
120
123
130
132
201
203
210
213
230
231
301
302
310
312
320
321.....

我如何获得112或222的输出?

从我理解的组合不是特定于排列的特定顺序。我正在寻找的是找到所有组合然后每个组合的每个排列。这可能吗?

2 个答案:

答案 0 :(得分:28)

你根本不想要排列。你想要笛卡尔积:

import itertools

def perm(n, seq):
    for p in itertools.product(seq, repeat=n):
        file.write("".join(p))
        file.write("\n")

perm(4, "0123")

答案 1 :(得分:7)

您似乎要寻找的是Cartesian product,而不是排列,也是由itertools提供的。

您可能会熟悉排列,组合,替换组合和笛卡尔积之间的差异,以确定哪种方法最适合您的应用,但很有可能,您正在寻找其他选项。

相关问题