简体   繁体   中英

Create combinations from a list and 3 ranges using itertools

I have the following:

a_list = [A,B,C]
r1 = range(1,5)
r2 = range(1,5)
r3 = range(1,5)

I would like to be able to find the various combinations of the elements in this list against the ranges. For example:

combi1 = [A, B, C, C, C]
combi2 = [A, A, B, C, C]
combi3 = [A, A, A, B, C]
combi4 = [A, B, B, C, C]

Etc.

I am able to do so if there were only 2 range , but I'm not sure how to fit 3 range in.

inc = range(1, 5)
desc = range(5, 1, -1)
combis = [list(itertools.chain(*(itertools.repeat(elem, n) for elem, n in zip(list, [i,j])))) for i,j in zip(inc,desc)]  

SOLUTION:

def all_exist(avalue, bvalue):
    return all(any(x in y for y in bvalue) for x in avalue)

combins = itertools.combinations_with_replacement(a_list, 5)
combins_list = [list(i) for i in combins]
for c in combins_list:
    if all_exist(a_list, c) == True:
        print c

output:

['A', 'A', 'A', 'B', 'C']
['A', 'A', 'B', 'B', 'C']
['A', 'A', 'B', 'C', 'C']
['A', 'B', 'B', 'B', 'C']
['A', 'B', 'B', 'C', 'C']
['A', 'B', 'C', 'C', 'C']

@doyz. I think this is may be what you are looking for :

From a list abc = ['A','B','C'] , you want to obtain its various combinations with replacement . Python has built-in itertools to do this.

import itertools

abc = ['A', 'B', 'C'];

combins = itertools.combinations_with_replacement(abc, 5);
combins_list = [list(i) for i in combins];

print(combins_list[0:10]);

This is the first 10 combinations with replacement :

[['A', 'A', 'A', 'A', 'A'], ['A', 'A', 'A', 'A', 'B'], ['A', 'A', 'A', 'A', 'C'], \
 ['A', 'A', 'A', 'B', 'B'], ['A', 'A', 'A', 'B', 'C'], ['A', 'A', 'A', 'C', 'C'], \
['A', 'A', 'B', 'B', 'B'], ['A', 'A', 'B', 'B', 'C'], ['A', 'A', 'B', 'C', 'C'], ['A', 'A', 'C', 'C', 'C']]

If you want to include all elements in abc , here is one way, that also includes the permutations :

import itertools
abc = ['A', 'B', 'C']; 
combins = itertools.combinations_with_replacement(abc, 5); 
combins_list = list(combins);
combins_all =[];
for i in combins_list:
    if len(set(i))==len(abc):
        combins_all.append(i);
print(combins_all);

include_permutations=[];
for i in combins_all:
    permut = list(itertools.permutations(i));
    include_permutations.append(permut);
print(include_permutations);

Is this okay?

*Note : itertools.combinations_woth_replacement and itertools.permutations do not result in a list, or tuple, but a different object itself, so you can't treat it as those.

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