Python函数从列表列表中返回2维列表

时间:2017-09-20 13:38:25

标签: python list

这里有一个蟒蛇问题。我想创建一个函数来从列表列表中返回一个二维列表。我在itertools中找不到这个函数。

Possibe输入=列出aa OR ab,如下所示(不同长度)

[[230, 'on'],
[230, 'off'],
[115, 'on'],
[115, 'off'],
[90, 'on'],
[90, 'off'],
[264, 'on'],
[264, 'off']]

ab的输出应为:

[[230, 12, -1, 'on'],
[230, 12, -1, 'off'],
[230, 9, -1, 'on'],
[230, 9, -1, 'off'],
....
[264, 5, -1, 'off']]
aa的输出应为:

{
  "myDB": {
    "data": "blah"
  }
}

1 个答案:

答案 0 :(得分:1)

我认为你要求的是一些可迭代的cartesian product,例如:

import itertools
import pprint

aa = [[230, 115, 90, 264], [12, 9, 5], [-1], ['on', 'off']]
ab = [[230, 115, 90, 264], ['on', 'off']]

for iterable in [aa, ab]:
    pprint.pprint(list(itertools.product(*aa)))

结果:

[(230, 12, -1, 'on'),
 (230, 12, -1, 'off'),
 (230, 9, -1, 'on'),
 (230, 9, -1, 'off'),
 (230, 5, -1, 'on'),
 (230, 5, -1, 'off'),
 (115, 12, -1, 'on'),
 (115, 12, -1, 'off'),
 (115, 9, -1, 'on'),
 (115, 9, -1, 'off'),
 (115, 5, -1, 'on'),
 (115, 5, -1, 'off'),
 (90, 12, -1, 'on'),
 (90, 12, -1, 'off'),
 (90, 9, -1, 'on'),
 (90, 9, -1, 'off'),
 (90, 5, -1, 'on'),
 (90, 5, -1, 'off'),
 (264, 12, -1, 'on'),
 (264, 12, -1, 'off'),
 (264, 9, -1, 'on'),
 (264, 9, -1, 'off'),
 (264, 5, -1, 'on'),
 (264, 5, -1, 'off')]
[(230, 12, -1, 'on'),
 (230, 12, -1, 'off'),
 (230, 9, -1, 'on'),
 (230, 9, -1, 'off'),
 (230, 5, -1, 'on'),
 (230, 5, -1, 'off'),
 (115, 12, -1, 'on'),
 (115, 12, -1, 'off'),
 (115, 9, -1, 'on'),
 (115, 9, -1, 'off'),
 (115, 5, -1, 'on'),
 (115, 5, -1, 'off'),
 (90, 12, -1, 'on'),
 (90, 12, -1, 'off'),
 (90, 9, -1, 'on'),
 (90, 9, -1, 'off'),
 (90, 5, -1, 'on'),
 (90, 5, -1, 'off'),
 (264, 12, -1, 'on'),
 (264, 12, -1, 'off'),
 (264, 9, -1, 'on'),
 (264, 9, -1, 'off'),
 (264, 5, -1, 'on'),
 (264, 5, -1, 'off')]