2个列表的Python组合(1个重复,1个非重复)

找到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))
上一篇:python – 使用概率表生成长度为K的N“随机”字符串


下一篇:python – itertools中的izip_longest:如何在迭代器中使用IndexError工作?