如何将一个列表中的元素插入到另一个列表中,生成所有可能的组合

大家好,我需要一些关于 python 列表的帮助。假设我有两个列表。


a = [3,1,5]

b = [2,4]

我想要的是连续插入列表 b 的元素(不改变 a 的顺序)生成新列表。例如。


ans = [[2,4,3,1,5],[2,3,4,1,5],[2,3,1,4,5],[2,3,1,5,4],[3,2,4,1,5]...]

感谢您的帮助,我希望我能够正确表达自己。


至尊宝的传说
浏览 149回答 2
2回答

qq_遁去的一_1

这不是最干净的方法,但这就是我的意思:from itertools import permutationsa = [3,1,5]b = [2,4]def a_order_is_same(perm):&nbsp; &nbsp; i3, i1, i5 = perm.index(3), perm.index(1), perm.index(5)&nbsp; &nbsp; return i3 < i1 < i5ans = [p for p in permutations(a+b) if a_order_is_same(p)]for p in ans:&nbsp; &nbsp; print(p)--------------------------------------------------(3, 1, 5, 2, 4)(3, 1, 5, 4, 2)(3, 1, 2, 5, 4)(3, 1, 2, 4, 5)(3, 1, 4, 5, 2)(3, 1, 4, 2, 5)(3, 2, 1, 5, 4)(3, 2, 1, 4, 5)(3, 2, 4, 1, 5)(3, 4, 1, 5, 2)(3, 4, 1, 2, 5)(3, 4, 2, 1, 5)(2, 3, 1, 5, 4)(2, 3, 1, 4, 5)(2, 3, 4, 1, 5)(2, 4, 3, 1, 5)(4, 3, 1, 5, 2)(4, 3, 1, 2, 5)(4, 3, 2, 1, 5)(4, 2, 3, 1, 5)

喵喔喔

我给你另一种选择。import itertools&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;a = [3,1,5]b = [2,4]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;c = [b +[a]][0] #0 to get only one level of nestedperm = [x for x in itertools.permutations(c, 3)]&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;ans = []这是获得“ans”输出的公式:for i in range(len(perm)):&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; groups = perm[i] #this is the subset like [2, 4, [3, 1, 5]]&nbsp; &nbsp; #flatten the list or returns integer&nbsp; &nbsp; clean = [y for x in groups for y in (x if isinstance(x,list) else [x])]&nbsp; &nbsp; ans.append(clean)&nbsp; &nbsp; print(clean)[[2, 4, 3, 1, 5], [2, 3, 1, 5, 4], [4, 2, 3, 1, 5], [4, 3, 1, 5, 2], [3, 1, 5, 2, 4], [3, 1, 5, 4, 2]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python