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

股西鑫来
  • 4
新手上路,请多包涵

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如何实现上面的排列组合?

回复
阅读 1.1k
3 个回答
✓ 已被采纳
from itertools import product
g = (list(zip(aa.keys(), i)) for i in product(*aa.values()))
wk9zvwof
  • 2
新手上路,请多包涵
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]]]
股西鑫来
  • 4
新手上路,请多包涵

其实我的数据结构是
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数据量大的时候,内存消耗太大,有没有高效的简洁的写法。

image

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏