简体   繁体   中英

How to find combination of n elements from list of lists while choosing single element for each list

Looking for combinations for n elements from list of lists but choosing only one element from each list. Eg

list =  [[a, b], [c,d], [e,f,g,h,i], [j,k,l,m, n], [o,p]..]

While choosing no more than one element from each list, I am trying to come up with different combinations

eg: for combination of n = 2 elements:

[a,c] [b,c], [c,j]...so on

for combination of n = 3 elements:

[a,c,e], [a,d,f]..so on

for combination of n = 4 elements:

[a, c, j, o], [a,c, i, p] ...

I tried using itertools combinations, but quickly running into issues. Any hints?

Is this what you are trying to achieve?

import itertools
from pprint import pprint

original_lst = [['a', 'b'], ['c','d'], ['e','f','g','h','i'], ['j','k','l','m','n'], ['o','p']]

def two_on_same_sublist(items, lst):
    for sub in lst:
        for i in itertools.combinations(items, 2):
            if all(x in sub for x in i):
                return True
            else:
                continue


def possible_combinations_of_items_in_sub_lists_no_rep(lst, n):
    flat_lst = [i for sublist in lst for i in sublist] # Make it one flat list
    return [i for i in itertools.combinations(flat_lst, n) if not two_on_same_sublist(i, lst)]

pprint(possible_combinations_of_items_in_sub_lists_no_rep(original_lst, 3))

I think you are looking for something like this.

Find the min and max size of sub list. Then create a dictionary with keys ranging from min to max.

Code:

from collections import defaultdict

c = defaultdict(list)

lst =  [['a','b'],
        ['c','d'],
        ['e','f','g','h','i'],
        ['j','k','l','m','n'],
        ['o','p'],
        ['q','r','s'],
        ['t','u','v'],
        ['w','x','y','z']]

a = min(map(len,lst)) #find min of sub list - here it will be 2
b = max(map(len,lst)) #find max of sub list - here it will be 5

for v in lst: #iterate thru the full list
    c[len(v)].append(v) #store values into a dictionary with key = len (sublist)

c = dict(c) #convert it back to normal dict

#iterate from min thru max and print the combinations
#skip if key not found in dictionary

for i in range (a, b+1):
    if i in c: print ('Combinations of n =',i, 'elements are :', c[i])

Output:

Combinations of n = 2 elements are : [['a', 'b'], ['c', 'd'], ['o', 'p']]
Combinations of n = 3 elements are : [['q', 'r', 's'], ['t', 'u', 'v']]
Combinations of n = 4 elements are : [['w', 'x', 'y', 'z']]
Combinations of n = 5 elements are : [['e', 'f', 'g', 'h', 'i'], ['j', 'k', 'l', 'm', 'n']]

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