简体   繁体   中英

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

I am a Python newbie and just come across the "itertools" module. 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

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). In this case, there are C(4+2,3)=20 combinations.

I wonder if there is an efficient way of using "itertools" to get the results. 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.

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 . 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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