找到 2 个列表的所有组合的最佳方法是什么,其中 1 个列表中的值可以重复,而另一个列表中的值不能重复?现在,我可以获得重复列表的所有组合,如下所示:
import itertools
rep = ['A','B','C', 'D']
norep = ['1','2','3','4']
for i in itertools.combinations_with_replacement(rep,4):
print i
我可以得到非重复列表的所有组合:
for i in itertool.combinations(norep,4):
print i
我可以得到两个列表的组合,就好像它们都是非重复的:
for i in itertools.product([0, 1], repeat=4):
print [(norep[j] if i else rep[j]) for j, i in enumerate(i)]
但是,我不知道如何获得重复列表和非重复列表的组合。我还想添加包含空值的组合,例如 ['A','1',Null]。
最佳答案
这就是我得到的。非常接近你的:
from itertools import chain
from itertools import combinations
# Huge name!
from itertools import combinations_with_replacement as cwr
from itertools import starmap
from itertools import product
from operator import add
def _weird_combinations(rep, no_rep, n_from_rep, n_from_norep):
return starmap(add, product(cwr(rep, n_from_rep),
combinations(no_rep, n_from_norep)))
def weird_combinations(rep, no_rep, n):
rep, no_rep = list(rep), list(no_rep)
# Allow Nones in the output to represent drawing less than n elements.
# If either input has None in it, this will be confusing.
rep.append(None)
# We can't draw more elements from no_rep than it has.
# However, we can draw as many from rep as we want.
least_from_rep = max(0, n-len(no_rep))
return chain.from_iterable(
_weird_combinations(rep, no_rep, n_from_rep, n-n_from_rep)
for n_from_rep in xrange(least_from_rep, n+1))
关于2 个列表的 Python 组合(1 个重复,1 个不重复),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17736217/