toledano
toledano

Reputation: 291

Filter iterator with list of values

I need to filter a itertool.combinations object with a list of elements.

This is the iterator:

from itertools import combinations 

items = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10', 'm1', 'm2', 'm3', 'm4', 'm5']
comb = combinations(items, 3)

Now, I can print the list of combinations with

for i in comb:
    print(i)

What I need is a list with all combination where ['m1', 'm2', 'm3', 'm4', 'm5'] are involves.

I tried to convert something like this

if 'm1' in ('m1', 'm2', 'm4'):
...     print('ok')
... 
ok

into this

ms1 = list(filter(lambda x: 'm1' in x, comb)) // empty list
ms2 = list(filter(lambda x: ['m1', 'm2', 'm3', 'm4', 'm5'] in x, comb)) // empty list

What I need is to get all combinations

Upvotes: 0

Views: 163

Answers (1)

rhurwitz
rhurwitz

Reputation: 2737

Assuming you want to create a list of only those combinations that include any one of the values in the target list of items (['m1', 'm2', 'm3', 'm4', 'm5']), then using set intersection may be appropriate.

Example:

from itertools import combinations 

items = ['b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'b10', 'm1', 'm2', 'm3', 'm4', 'm5']
item_combinations = combinations(items, 3)

target_items = {'m1', 'm2', 'm3', 'm4', 'm5'}
target_item_combinations = [
    one_combination
    for one_combination in item_combinations
    if set(one_combination) & target_items
]

Upvotes: 1

Related Questions