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

时间:2018-06-08 19:40:00

标签: python python-3.x list dictionary multidimensional-array

我的目标是生成一个包含指定组中所有元素组合的列表。输出应该是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)

输出:[[[' one',' four'],...,[' nine',' 12'] ]

所需的输出:[[' one',' four'],...,[' nine',' 12'] ]

1 个答案:

答案 0 :(得分:1)

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

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

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