获取 3D 列表而不是 2D 列表



我的目标是生成一个列表,其中包含来自指定组的所有元素组合。输出应该是 2D 列表,但我无法生成除 3D 列表以外的任何内容。我可以直接生成 2D 列表,还是需要将 3D 列表转换为 2D 列表?如果是这样,如何?

# 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)

输出: [['一', '四'],..., ['九', '十二']]]

期望输出: [["一"、"四"], ..., ["九"、"十二"]]

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

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]))

或:

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

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

最新更新