python如何实现上面的排列组合?

aa = [[[1, 2, 3, 5], [1, 2, 3, 6]], [[1, 2, 3, 8], [1, 2, 3, 9]]]
bb = [[1, 2, 5], [2, 6, 85]]

aa和bb依次组合形成新的列表

cc=[[[1, 2, 3, 5], [1, 2, 3, 6],[1, 2, 5]],[[1, 2, 3, 5], [1, 2, 3, 6],[2, 6, 85]],[[1, 2, 3, 8], [1, 2, 3, 9],[1, 2, 5]],[[1, 2, 3, 8], [1, 2, 3, 9],[2, 6, 85]]]

python如何实现上面的排列组合?


回答:

from itertools import product

g = (list(zip(aa.keys(), i)) for i in product(*aa.values()))


回答:

aa = [[[1, 2, 3, 5], [1, 2, 3, 6]], [[1, 2, 3, 8], [1, 2, 3, 9]]]

bb = [[1, 2, 5], [2, 6, 85]]

cc = []

for aitem in aa:

for bitem in bb:

cc.append(aitem + [bitem])

print(cc)

#[[[1, 2, 3, 5], [1, 2, 3, 6], [1, 2, 5]], [[1, 2, 3, 5], [1, 2, 3, 6], [2, 6, 85]], [[1, 2, 3, 8], [1, 2, 3, 9], [1, 2, 5]], [[1, 2, 3, 8], [1, 2, 3, 9], [2, 6, 85]]]


回答:

其实我的数据结构是
aa = {'a': [1, 2, 3], 'b': [2, 3, 5, 6], 'c': [5, 6, 9]}
我就是把这个形成从头到尾的排列组合,我开始采用的法子是:

con = []

t = 0

for k, v in zip(aa.keys(), aa.values()):

if t < 1:

con = list(map(lambda x: [[str(k), str(x)]], v))

t = 2

else:

cons = []

for i in range(len(con)):

for s in v:

tmp0 = con[i].copy()

tmp = []

tmp.append(str(k))

tmp.append(str(s))

tmp0.append(tmp)

cons.append(tmp0)

con = cons.copy()

print(con)

最终得到了我想要的组合
[[['a', '1'], ['b', '2'], ['c', '5']], [['a', '1'], ['b', '2'], ['c', '6']], [['a', '1'], ['b', '2'], ['c', '9']], [['a', '1'], ['b', '3'], ['c', '5']], [['a', '1'], ['b', '3'], ['c', '6']], [['a', '1'], ['b', '3'], ['c', '9']], [['a', '1'], ['b', '5'], ['c', '5']], [['a', '1'], ['b', '5'], ['c', '6']], [['a', '1'], ['b', '5'], ['c', '9']], [['a', '1'], ['b', '6'], ['c', '5']], [['a', '1'], ['b', '6'], ['c', '6']], [['a', '1'], ['b', '6'], ['c', '9']], [['a', '2'], ['b', '2'], ['c', '5']], [['a', '2'], ['b', '2'], ['c', '6']], [['a', '2'], ['b', '2'], ['c', '9']], [['a', '2'], ['b', '3'], ['c', '5']], [['a', '2'], ['b', '3'], ['c', '6']], [['a', '2'], ['b', '3'], ['c', '9']], [['a', '2'], ['b', '5'], ['c', '5']], [['a', '2'], ['b', '5'], ['c', '6']], [['a', '2'], ['b', '5'], ['c', '9']], [['a', '2'], ['b', '6'], ['c', '5']], [['a', '2'], ['b', '6'], ['c', '6']], [['a', '2'], ['b', '6'], ['c', '9']], [['a', '3'], ['b', '2'], ['c', '5']], [['a', '3'], ['b', '2'], ['c', '6']], [['a', '3'], ['b', '2'], ['c', '9']], [['a', '3'], ['b', '3'], ['c', '5']], [['a', '3'], ['b', '3'], ['c', '6']], [['a', '3'], ['b', '3'], ['c', '9']], [['a', '3'], ['b', '5'], ['c', '5']], [['a', '3'], ['b', '5'], ['c', '6']], [['a', '3'], ['b', '5'], ['c', '9']], [['a', '3'], ['b', '6'], ['c', '5']], [['a', '3'], ['b', '6'], ['c', '6']], [['a', '3'], ['b', '6'], ['c', '9']]]

但是当aa数据量大的时候,内存消耗太大,有没有高效的简洁的写法。

python如何实现上面的排列组合?

以上是 python如何实现上面的排列组合? 的全部内容, 来源链接: utcz.com/a/156522.html

回到顶部