在python中如何实现列表中元素的所有排列组合?如输入为['1','2','3']和2输出为['

在python中如何实现列表中元素的所有排列组合?如输入为['1','2','3']和2输出为['11','12','13','21','22','23','31','32','33']如输入为['1','2','3']和3输出为['111','112','113','121','122','123','131','132','133','211','212','213','221','222','223','231','232','233','311','312','313','321','322','323','331','332','333']

第1个回答  2016-05-04
#!/usr/bin/python
#Two method for generate a list whose item is all possible permutation and combination come from every item of many list.

A = ['1', '2']
B = ['a', 'b', 'c']
C = ['A', 'B', 'C', 'D']

retList = []
for a in A:
for b in B:
for c in C:
retList.append((a,b,c))
print retList

print '*' * 40

def myfunc(*lists):
#list all possible composition from many list, each item is a tuple.
#Here lists is [list1, list2, list3], return a list of [(item1,item2,item3),...]

#len of result list and result list.
total = reduce(lambda x, y: x * y, map(len, lists))
retList = []

#every item of result list.
for i in range(0, total):
step = total
tempItem = []
for l in lists:
step /= len(l)
tempItem.append(l[i/step % len(l)])
retList.append(tuple(tempItem))

return retList

print myfunc(A,B,C)本回答被网友采纳
相似回答