【发布时间】:2018-11-18 21:57:15
【问题描述】:
我的目标是生成一个列表,其中包含来自指定组的所有元素组合。输出应该是 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', 'twelve']]
【问题讨论】:
-
可以使用stackoverflow.com/questions/45910827/… 完成从 3D 到 2D 的转换,这首先没有解决创建不需要的 3D 列表的问题。
标签: python python-3.x list dictionary multidimensional-array