我的输出的一个重要部分是能够识别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')]
我知道它正在删除重复项,或者我的代码可能完全丢失了一些东西,因为我从输出中遗漏了[('a','a'), ('b','b'), ('c','c')]
答案 0 :(得分:1)
你可以试试这个。使用排列更改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')]