Python 获取三维列表而不是二维列表

Python 获取三维列表而不是二维列表,python,python-3.x,list,dictionary,multidimensional-array,Python,Python 3.x,List,Dictionary,Multidimensional Array,我的目标是生成一个包含指定组中所有元素组合的列表。输出应该是一个2D列表,但我无法生成3D列表以外的任何内容。我是否可以直接生成二维列表,或者是否需要将三维列表转换为二维列表?如果是,怎么做 # elements comprising each of groups a1-a4 a1 = ['one','two','three'] a2 = ['four','five','six'] a3 = ['seven','eight','nine'] a4 = ['ten','eleven','twelv

我的目标是生成一个包含指定组中所有元素组合的列表。输出应该是一个2D列表,但我无法生成3D列表以外的任何内容。我是否可以直接生成二维列表,或者是否需要将三维列表转换为二维列表?如果是,怎么做

# elements comprising each of groups a1-a4
a1 = ['one','two','three']
a2 = ['four','five','six']
a3 = ['seven','eight','nine']
a4 = ['ten','eleven','twelve']

# each row in b specifies two or more groups, whereby all combinations of one
# element from each group is found
b  = [[a1,a2],
      [a3, a4]]

# map(list,...) converts tuples from itertools.product(*search) to lists
# list(map(list,...)) converts map object into list
# [...] performs list comprehension
l = [list(map(list, itertools.product(*search))) for search in b]
print(l)
输出:[['1'、['4']、…、['9'、['12']]


所需输出:['1','4'],…,['9','12']]

显然,您可以按如下方式创建列表:

l = []
for search in b:
    l += list(map(list, itertools.product(*search)))
但如果你想坚持列表理解,你可以:

l = list(itertools.chain(*[map(list, itertools.product(*search)) for search in b]))
或:


它创建并链接两个笛卡尔乘积,然后将元组映射到列表。

使用此方法可以完成从3D到2D的转换,但它并没有首先解决创建不需要的3D列表的问题。
l = list(map(list, itertools.chain(*[itertools.product(*search) for search in b])))