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

标签 python python-2.7 combinations product python-itertools

找到 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/

相关文章:

Python参数范围-相同的对象?

Python、__slots__、继承和类变量==>属性是只读的bug

python-2.7 - 使用 docx 库打开有密码的 Word 文档

Python - PyQt Matplotlib 绘图定位

r - 从 M 中得到所有长度为 N 的组合

python - 如何解析txt文件末尾的json格式文本

python - 使用自定义比较的排序键函数

python-2.7 - 获取选择字段的值而不是键

java - 在java中生成给定集合的nCr组合

python - 如何使用 python 中的一组标签生成标记(分类)一组对象的所有可能方式?