使用Python将字符串中字符的所有可能组合写入文件

问题描述:

我有一个字符串s =“abcde”。我想要生成所有可能的排列并将它们写入txt文件中。 OUT FILE.TXT使用Python将字符串中字符的所有可能组合写入文件

一个 b Ç d AA AB 交流 广告 AE BA BB BC BD 是 CA CB 立方厘米 CD CE 哒 分贝 dc dd de EA EB EC 版 EE ... ... eeeda eeedb eeedc eeedd eeede eeeea eeeeb eeeec eeeed EEEEE

我用迭代工具,但它始终启动与aaaaa。

+1

分享您的代码,请。看起来你只需要产生长度为1,然后是2,然后是3等的'排列'......直到你想要的长度,这可以通过'for'循环容易地完成。 – Julien

+0

这不是排列!告诉我们你的代码和预期的输出与实际输出 – alfasin

itertools.permutations需要2个参数,可迭代和排列的长度。如果你没有指定第二个agrument,它默认为len(iterable)。要得到所有的长度,你需要打印排列每个长度:

import itertools 
s = "abcde" 
for i in range(len(s)): 
    for permutation in (itertools.permutations(s, i+1)): 
     print ("".join(permutation)) 

来源:https://docs.python.org/2/library/itertools.html#itertools.permutations

+0

是的,确实排列需要两个元素。我在急着写,忘了:) – campovski

+0

这是不正确的每OP的要求。 –

import itertools 

s="abcde" 

def upto_n(s,n): 

    out = [] 

    for i in range(1,n+1,1): 

     out += list(itertools.combinations(s, i)) 

    return out 

print upto_n(s,2) 
print upto_n(s,3) 

输出

[('a',), ('b',), ('c',), ('d',), ('e',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e')] 

[('a',), ('b',), ('c',), ('d',), ('e',), ('a', 'b'), ('a', 'c'), ('a', 'd'), ('a', 'e'), ('b', 'c'), ('b', 'd'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('d', 'e'), ('a', 'b', 'c'), ('a', 'b', 'd'), ('a', 'b', 'e'), ('a', 'c', 'd'), ('a', 'c', 'e'), ('a', 'd', 'e'), ('b', 'c', 'd'), ('b', 'c', 'e'), ('b', 'd', 'e'), ('c', 'd', 'e')] 
+0

这对于每个OP的输出也是不正确的。他们也想重复角色。 –

使用可从PY3 itertools.productyield from语法。 3):

import itertools 

def foo(x): 
    for i in range(1, len(x) + 1): 
     yield from(itertools.product(*([s] * i))) 

for x in foo('abc'): # showing you output for 3 characters, output explodes combinatorially 
    print(''.join(x)) 

a 
b 
c 
aa 
ab 
ac 
ba 
bb 
bc 
ca 
cb 
cc 
aaa 
aab 
aac 
aba 
abb 
abc 
aca 
acb 
acc 
baa 
bab 
bac 
bba 
bbb 
bbc 
bca 
bcb 
bcc 
caa 
cab 
cac 
cba 
cbb 
cbc 
cca 
ccb 
ccc 

要写入一个文件,你应该打开一个第一和一个循环调用foo

with open('file.txt', 'w') as f: 
    for x in foo('abcde'): 
     f.write(''.join(x) + '\n')