2017-08-31 24 views
0

我有一個字符串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

回答

-1

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的要求。 –

-1
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的輸出也是不正確的。他們也想重複角色。 –

0

使用可從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') 
相關問題