简体   繁体   English

如何使用python生成仅重复一个元素的组合

[英]How to generate combinations with repetition of only one element using python

I am a Python newbie and just come across the "itertools" module. 我是一个Python新手,只是遇到了“itertools”模块。 I want to create this specific type of combinations with multiple lists that: 我想用多个列表创建这种特定类型的组合:

1) repeat the first element of the latter list 2) the latter value is in ascending order within a combination 1)重复后一个列表的第一个元素2)后一个值在组合中按升序排列

eg for these two lists 例如,对于这两个列表

    a=[1,2,3]
    b=[None,4,5,6]

The desired outcome is 期望的结果是

    [(1, None), (2, None), (3, None)]
    [(1, None), (2, None), (3, 4)]
    [(1, None), (2, None), (3, 5)]
    [(1, None), (2, None), (3, 6)]
    [(1, None), (2, 4), (3, None)]
    [(1, None), (2, 4), (3, 5)]
    [(1, None), (2, 4), (3, 6)]
    [(1, None), (2, 5), (3, None)]
    [(1, None), (2, 5), (3, 6)]
    [(1, None), (2, 6), (3, None)]
    [(1, 4), (2, None), (3, None)]
    [(1, 4), (2, None), (3, 5)]
    [(1, 4), (2, None), (3, 6)]
    [(1, 4), (2, 5), (3, None)]
    [(1, 4), (2, 5), (3, 6)]
    [(1, 4), (2, 6), (3, None)]
    [(1, 5), (2, None), (3, None)]
    [(1, 5), (2, None), (3, 6)]
    [(1, 5), (2, 6), (3, None)]
    [(1, 6), (2, None), (3, None)]

That is C(n+2,m) combinations in total, where n=len(b) and m=len(a). 这是总共C(n + 2,m)个组合,其中n = len(b),m = len(a)。 In this case, there are C(4+2,3)=20 combinations. 在这种情况下,存在C(4 + 2,3)= 20种组合。

I wonder if there is an efficient way of using "itertools" to get the results. 我想知道是否有一种使用“itertools”来获得结果的有效方法。 Also, please note that there may be more than 2 lists, eg there could be ac=[None,7,8,9,10], resulting in 3 elements within each tuple. 此外,请注意,可能有超过2个列表,例如可能有ac = [None,7,8,9,10],导致每个元组中有3个元素。

EDIT: I have managed to get what I want using the code below, which works although inefficient. 编辑:我已经设法得到我想要的使用下面的代码,虽然效率低,但效果不错。 Please let me know if you have a better way of solving this issue. 如果您有更好的方法来解决这个问题,请告诉我。 Thank you:) 谢谢:)

a=[1,2,3]
b=[4,5,6]
def create_none(lst):
    none_list=[]
    for Index in range(len(lst)):
        none_list.append(None)
    return none_list
extended_list=create_none(a)[:]
extended_list.extend(b)  

for i in itertools.combinations(extended_list,len(a)):
    sublist=list(zip(a,i))
    print(sublist)

There is a function in itertools module: itertools.product . itertools模块中有一个函数: itertools.product It does exactly what you need. 它完全符合您的需求。

Example: 例:

a = [None,1,2]
list(itertools.product(a, repeat=3))

[(None, None, None),
 (None, None, 1),
 (None, None, 2),
 (None, 1, None),
 (None, 1, 1),
 (None, 1, 2),
 (None, 2, None),
 (None, 2, 1),
 (None, 2, 2),
 (1, None, None),
 (1, None, 1),
 (1, None, 2),
 (1, 1, None),
 (1, 1, 1),
...

Your problem can be solved by this code: 您的问题可以通过以下代码解决:

[list(zip(a, elem))for elem in itertools.product(b, repeat=3)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM