假设有两个列表。
List1 = [1,3,5,7,9]
List2 = [2,4,6,8,10]
我想打印所有可能性,没有符合以下模式的重复:
Res = [odd,even,odd,even,odd,even,odd,even,odd,even]
例如,
Res = [1,2,3,4,5,6,7,8,9,10]
Res = [1,2,5,4,3,6,9,8,7,10]
Res = [3,2,1,4,9,6,5,10,7,8]
我尝试使用itertools.product,但我不知道如何迭代它。
答案 0 :(得分:1)
>>> List1 = [1,3,5,7,9]
>>> List2 = [2,4,6,8,10]
>>> import itertools
>>> list(map(lambda x:list(itertools.chain(*zip(*x))), (itertools.product(itertools.permutations(List1), itertools.permutations(List2)))))
答案 1 :(得分:0)
使用numpy,像:
np.ravel(np.column_stack((List1, List2)))
答案 2 :(得分:0)
如果列表可以包含奇数和偶数值的混合并且模式标准可以变化,这是一个通用的解决方案:
import itertools as it
def combine_and_filter(lst1, lst2, criteria):
perms = it.permutations(it.chain.from_iterable(zip(lst1, lst2)))
return filter(lambda perm: all((v % 2 == c for v, c in zip(perm, criteria))), perms)
List1 = [1, 4, 7]
List2 = [2, 5, 8]
criteria1 = (1, 0, 1, 0, 1, 0, ) # one for odd numbers, 0 for even
criteria2 = (1, 1, 0, 0, 1, 0, )
criteria3 = (0, 1, 1, 0, 0, 1, )
res1 = list(combine_and_filter(List1, List2, criteria1))
res2 = list(combine_and_filter(List1, List2, criteria2))
res3 = list(combine_and_filter(List1, List2, criteria3))
print(res1)
print(res2)
print(res3)
产生:
[(1,2,5,4,7,8),(1,2,5,8,7,4),(1,2,7,4,5,8),(1,2) ,7, 8,5,4),(1,4,5,2,7,8),(1,4,5,8,7,2),(1,4,7,2,5,8), (1,4,7,8,5,2),(1,8,5,2,7,4),(1,8,5,4,7,2),(1,8,7, 2,5,4),(1,8,7,4,5,2),(5,2,1,4,7,8),(5,2,1,8,7,4), (5,2,7,4,1,8),(5,2,7,8,1,4),(5,4,1,2,7,8),(5,4,1, 8,7,2),(5,4,7,2,1,8),(5,4,7,8,1,2),(5,8,1,2,7,4), (5,8,1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),(8,1,7,4,2,5),(8,5,1,2,4,7),(8,5,1, 4,2,7),(8,5,7,2,4,1),(8,5,7,4,2,1),(8,7,1,2,4,5), (8,7,1,4,2,5),(8,7,5,2,4,1),(8,7,5,4,2,1)]
注1:缩短列表以减少结果集
note2:我假设每个排列都有一个元组而不是列表。如果没有,创建它们用
替换返回值很简单return map(list, filter(lambda perm: all((v % 2 == c for v, c in zip(perm, criteria))), perms))