在 python 中所有可能的组合中将一个项目列表替换为另一个列表
Replace one list of items with another list in all possible combinations in python
我想在所有可能的组合中用另一个列表替换一个项目列表,不重复,例如
list1 =[1,2,3]
list2 = [4,5]
Output =
[1,2,3],
[1,2,4],
[1,2,5],
[1,4,3],
[1,5,3],
[4,2,3],
[5,2,3],
[1,4,5],
[4,2,5],
[4,5,3]
我已经尝试 itertools.product 使用 zip,但结果并不是我想要的,我想知道是否有人知道如何执行此操作,非常感谢您的帮助。 :)
解决方法如下:
from itertools import combinations
output = list(combinations(list1 + list2, 3))
OP 保留 list1 的顺序,并用 list2 中的元素屏蔽它。
我创建了一个 list2 的幂集,并用 Nones 扩展它以匹配 list1 的长度(= helper)。然后我迭代 helper 的独特排列,用另一个数组屏蔽一个数组以隐藏 list1 的部分,其中屏蔽包含 not-None 值。
动力组来自:How to get all subsets of a set? (powerset)
from itertools import chain, combinations, permutations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
list1 = [1, 2, 3]
list2 = [4, 5]
solutions = []
for s in powerset(list2):
# for every possibility of list2
helper = [None] * (len(list1) - len(s))
helper.extend(s)
# create something like [None, None, 4]
for perm in set(permutations(helper, len(helper))):
# for each permutation of the helper, mask out nones
solution = []
for listchar, helperchar in zip(list1, perm):
if helperchar != None:
solution.append(helperchar)
else:
solution.append(listchar)
solutions.append(solution)
print(solutions)
# [[1, 2, 3], [4, 2, 3], [1, 4, 3], [1, 2, 4], [1, 2, 5], [5, 2, 3], [1, 5, 3], [1, 5, 4], [4, 2, 5], [5, 2, 4], [5, 4, 3], [1, 4, 5], [4, 5, 3]]
我想在所有可能的组合中用另一个列表替换一个项目列表,不重复,例如
list1 =[1,2,3]
list2 = [4,5]
Output =
[1,2,3],
[1,2,4],
[1,2,5],
[1,4,3],
[1,5,3],
[4,2,3],
[5,2,3],
[1,4,5],
[4,2,5],
[4,5,3]
我已经尝试 itertools.product 使用 zip,但结果并不是我想要的,我想知道是否有人知道如何执行此操作,非常感谢您的帮助。 :)
解决方法如下:
from itertools import combinations
output = list(combinations(list1 + list2, 3))
OP 保留 list1 的顺序,并用 list2 中的元素屏蔽它。 我创建了一个 list2 的幂集,并用 Nones 扩展它以匹配 list1 的长度(= helper)。然后我迭代 helper 的独特排列,用另一个数组屏蔽一个数组以隐藏 list1 的部分,其中屏蔽包含 not-None 值。
动力组来自:How to get all subsets of a set? (powerset)
from itertools import chain, combinations, permutations
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
list1 = [1, 2, 3]
list2 = [4, 5]
solutions = []
for s in powerset(list2):
# for every possibility of list2
helper = [None] * (len(list1) - len(s))
helper.extend(s)
# create something like [None, None, 4]
for perm in set(permutations(helper, len(helper))):
# for each permutation of the helper, mask out nones
solution = []
for listchar, helperchar in zip(list1, perm):
if helperchar != None:
solution.append(helperchar)
else:
solution.append(listchar)
solutions.append(solution)
print(solutions)
# [[1, 2, 3], [4, 2, 3], [1, 4, 3], [1, 2, 4], [1, 2, 5], [5, 2, 3], [1, 5, 3], [1, 5, 4], [4, 2, 5], [5, 2, 4], [5, 4, 3], [1, 4, 5], [4, 5, 3]]