问题
Possible Duplicate:
Power set and Cartesian Product of a set python
With Python Itertools.permutations() I would like to receive and output of permutations with repeating characters. For an example this my function below and its current output.
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')
the output is:
012
013
021
023
031
032
102
103
120
123
130
132
201
203
210
213
230
231
301
302
310
312
320
321.....
how would I get an output like 112 or 222?
from what I understand combinations are not order specific where permutations are. what I am looking for is finding all combinations then every permutation for each combination. Is this possible?
回答1:
You don't want permutations at all. You want the cartesian product:
import itertools
def perm(n, seq):
for p in itertools.product(seq, repeat=n):
file.write("".join(p))
file.write("\n")
perm(4, "0123")
回答2:
What you seem to be looking for is a Cartesian product, not a permutation, which is also provided by itertools.
You might do well to familiarize yourself with the differences between permutation, combination, combination with replacement, and Cartesian product to decide what works best your application, but chances are, you're looking for another of the options.
来源:https://stackoverflow.com/questions/14006867/python-itertools-permutations-how-to-include-repeating-characters