【问题标题】:Getting 3D list rather than 2D list获取 3D 列表而不是 2D 列表
【发布时间】: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']]

【问题讨论】:

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


【解决方案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])))

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-29
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多