简体   繁体   English

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

[英]Getting 3D list rather than 2D list

My goal is to produce a list comprising all combination of elements from specified groups. 我的目标是产生一个列表,其中包含指定组中元素的所有组合。 The output should be a 2D list but I am unable to generate anything other than a 3D list. 输出应该是2D列表,但是我无法生成3D列表以外的任何东西。 Can I generate the 2D list directly, or is it necessary to convert the 3D list to a 2D list? 我可以直接生成2D列表,还是有必要将3D列表转换为2D列表? If so, how? 如果是这样,怎么办?

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

Output: [[['one', 'four'], ..., ['nine', 'twelve']]] 输出:[[['one','four'],...,['nine','twelve']]]

Desired Output: [['one', 'four'], ..., ['nine', 'twelve']] 所需的输出:[['一个','四个'],...,['九','十二']]

Obviously, you can create your list as follows: 显然,您可以如下创建列表:

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

But if you want to stick with a list comprehension, you can do: 但是,如果您想坚持使用列表理解,可以执行以下操作:

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

Or: 要么:

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

It creates and chains the two cartesian products, and then maps the tuples to lists. 它创建并链接两个笛卡尔积,然后将元组映射到列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM