假设给出多个列表,然后从每个列表中取一个元素,构成一个元组,列出所有这样的元组的排列组合。

这里给出两个算法:一个需要循环嵌套,一个不用,代码和输出如下。

算法

#!/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')]