【发布时间】:2015-02-16 20:50:02
【问题描述】:
我正在尝试使用递归在 python 中生成列表排列。
import copy
def perm(seq):
if len(seq) == 1:
return seq
else:
nseq = perm(seq[1:])
return zip_letter(seq[0], nseq)
def zip_letter(c, seq):
lis = []
for i in range(len(seq)+1):
seq.insert(i, c)
lis.append(copy.deepcopy(seq))
seq.pop(i)
return lis
print perm(['a', 'b', 'c'])
输出是 [['a', ['b', 'c'], ['c', 'b']], [['b', 'c'], 'a', ['c', 'b' ]], [['b', 'c'], ['c', 'b'], 'a']]
看起来不错,但插入格式不正确。 我错过了什么?
【问题讨论】:
-
除非你故意自己重写它作为练习,否则你应该使用
itertools.permutations。
标签: python