分类: Python/Ruby
2013-01-24 12:23:53
一个算法, 给出多个列表,然后从每个列表中取一个元素,构成一个元组,列出所有这样的元组,
两个方法,一个需要循环嵌套,一个不用,代码和输出如下:
#!/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)
输出:
[('1', 'a', 'A'), ('1', 'a', 'B'), ('1', 'a', 'C'), ('1', 'a', 'D'), ('1', 'b', 'A'), ('1', 'b', 'B'), ('1', 'b', 'C'), ('1', 'b', 'D'), ('1', 'c', 'A'), ('1', 'c', 'B'), ('1', 'c', 'C'), ('1', 'c', 'D'), ('2', 'a', 'A'), ('2', 'a', 'B'), ('2', 'a', 'C'), ('2', 'a', 'D'), ('2', 'b', 'A'), ('2', 'b', 'B'), ('2', 'b', 'C'), ('2', 'b', 'D'), ('2', 'c', 'A'), ('2', 'c', 'B'), ('2', 'c', 'C'), ('2', 'c', 'D')]
****************************************
[('1', 'a', 'A'), ('1', 'a', 'B'), ('1', 'a', 'C'), ('1', 'a', 'D'), ('1', 'b', 'A'), ('1', 'b', 'B'), ('1', 'b', 'C'), ('1', 'b', 'D'), ('1', 'c', 'A'), ('1', 'c', 'B'), ('1', 'c', 'C'), ('1', 'c', 'D'), ('2', 'a', 'A'), ('2', 'a', 'B'), ('2', 'a', 'C'), ('2', 'a', 'D'), ('2', 'b', 'A'), ('2', 'b', 'B'), ('2', 'b', 'C'), ('2', 'b', 'D'), ('2', 'c', 'A'), ('2', 'c', 'B'), ('2', 'c', 'C'), ('2', 'c', 'D')]