Python: generate a list containing lists from several lists
本问题已经有最佳答案,请猛点这里访问。
我有以下列表:
1 2 3 | [1,2,3] [1] [1,2,3,4] |
从上面,我想生成一个列表,其中包含:
1 2 3 | [[1,1,1],[1,1,2],[1,1,3],[1,1,4], [2,1,1], [2,1,2], [2,1,3], [2,1,4], [3,1,2], [3,1,3],[3,1,4]] |
这个过程叫什么?
生成python列表的阶乘?
有没有内置的图书馆能做到这一点?
使用
1 2 3 | >>> import itertools >>> [list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])] [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]] |
1 2 3 4 | >>> lists = [[1,2,3], [1], [1,2,3,4]] >>> from itertools import product >>> map(list, product(*lists)) [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]] |
注:使用
1 2 3 4 | inputList = [[1,2,3], [1], [1,2,3,4]] import itertools print [list(item) for item in itertools.product(*inputList)] |
产量
1 2 3 4 5 6 7 8 9 10 11 12 | [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 1, 4], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 1, 4], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 1, 4]] |
正如其他答案中所建议的那样,
1 | result = [[x,y,z] for x in [1,2,3] for y in [1] for z in [1,2,3,4]] |
以下是使用Normal for Loops的相同之处,这可能会使其更具可读性:
1 2 3 4 5 | result = [] for x in [1,2,3]: for y in [1]: for z in [1,2,3,4]: result.append([x, y, z]) |