有时程序需求需要将list中的元素进行随机不重复组合,并且组合对是有序的,递归可以很好的解决,不多说,程序如下:
def combine(l, n):
answers = []
one = [
0] * n
def next_c(li = 0, ni = 0):
if ni == n:
answers.append(copy.copy(one))
return
for lj
in xrange(li, len(l)):
one[ni] = l[lj]
next_c(lj +
1, ni +
1)
next_c()
return answers
l = [
'1',
'3',
'2']
l.sort()
print combine(l,
2)
[[
'1',
'2'], [
'1',
'3'], [
'2',
'3']]