[英]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.从列表列表中寻找 n 个元素的组合,但从每个列表中仅选择一个元素。 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:例如:对于
n = 2
元素的组合:
[a,c] [b,c], [c,j]...so on
for combination of n = 3
elements:对于
n = 3
元素的组合:
[a,c,e], [a,d,f]..so on
for combination of n = 4
elements:对于
n = 4
元素的组合:
[a, c, j, o], [a,c, i, p] ...
I tried using itertools combinations, but quickly running into issues.我尝试使用 itertools 组合,但很快就遇到了问题。 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.
然后创建一个字典,其键范围从 min 到 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: 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']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.