2015-08-18 120 views
1

我使用這個代碼textwrap工作:的Python 3.4.3 - 如何使itertools

#!/usr/bin/env python3 
# -*- coding: utf-8 -*- 

import textwrap 
import itertools 

a = [] 

a.append('word1') 
a.append('word2') 
a.append('word3') 
a.append('word4') 
a.append('word5') 
a.append('word6') 
a.append('word7') 
a.append('word8') 
a.append('word9') 
a.append('word10') 

for permutation in itertools.permutations(a,): 
    permutation = textwrap.TextWrapper(len=60,break_long_words=False,replace_whitespace=False) 
    print(' '.join(permutation))  

,並從herehere一些信息,但解決不了我的問題。

我只是想將這些單詞排列成具有60個字符長度的所有可能的組合不可重複的短語。

+0

我不確定你想用什麼文本包裝。另外,你正在覆蓋for循環中的排列。 – poke

+0

我試圖只打印60個字符長的短語。 –

回答

1

這將打印,當合併成一個單一的字符串,具有長度60的所有排列:

for permutation in itertools.permutations(a): 
    s = ' '.join(permutation) 
    if len(s) == 60: 
     print(s) 

但它並沒有多大意義,反正要做到這一點,因爲一個序列的排列總會包含該序列的所有元素,因此組合的字符串將始終具有相同的長度,並且只有內部的單詞的順序發生變化。

所以你可以先做檢查,然後循環排列。

或者您可以生成可以改變長度的組合。

+0

無法正常工作。它只是讓我進入一個永遠的循環,並不打印60 char len =/ –

+0

不,這不能是一個無限循環。但很可能你沒有找到任何結果,尤其是對於你問題中的那些示例字符串(沒有組合會給你一個長度爲60的字符串)。 – poke

+0

我正在嘗試此操作並不起作用。 '!#在/ usr/bin中/ env的python3 # - * - 編碼:UTF-8 - * - 進口textwrap 進口itertools 一個=' 只是測試這種嘗試,使這個work'.split() 如果len(s)== 60: print(s)' –