2016-10-11 46 views
0

我輸出的一個重要部分是能夠識別finalList的長度,但地方在我的代碼,重複項被刪除,我無法揣摩出我的代碼在哪裏被重複刪除?

from itertools import chain, permutations 
allPos = [] 
first_list = ['a','b','c'] 
match_list = [['a','b','c'], ['a','b','c']] 

for i in range(1,30): 
    for phrase in permutations(first_list, i): 
     for ind, letter in enumerate(chain.from_iterable(phrase)): 
      if ind >= len(match_list) or letter not in match_list[ind]: 
       break 
     else: 
      allPos.append(phrase) 

finalList = [] 

for i in allPos: 
    if len(i) == len(allPos[-1]): 
     finalList.append(i) 

print(finalList) 

輸出

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

我知道這是刪除重複的,或者我的代碼只是失去了一些東西完全是因爲我從我的輸出

+5

這裏:['permutations'](https://docs.python.org/2/library/itertools.html#itertools.permutations)? – zvone

+0

是否應該縮進? – kpie

+0

我已閱讀文檔@zvone – oneman

回答

1

你可以用這個試試拖欠[('a','a'), ('b','b'), ('c','c')]。使用排列更改iterable

from itertools import chain, permutations 
... 
... 
for i in range(1,30): 
    # change iterable 
    for phrase in permutations([j for ele in match_list for j in ele], i): 

... 
for i in set(allPos): 
    if len(i) == len(allPos[-1]): 
     finalList.append(i) 

print (sorted(finalList)) 
[('a', 'a'), ('a', 'b'), ('a', 'c'), ('b', 'a'), ('b', 'b'), ('b', 'c'), ('c', 'a'), ('c', 'b'), ('c', 'c')]