簡體   English   中英

如何在為每個列表選擇單個元素時從列表列表中查找 n 個元素的組合

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

從列表列表中尋找 n 個元素的組合,但從每個列表中僅選擇一個元素。 例如

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

雖然從每個列表中選擇不超過一個元素,但我試圖提出不同的組合

例如:對於n = 2元素的組合:

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

對於n = 3元素的組合:

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

對於n = 4元素的組合:

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

我嘗試使用 itertools 組合,但很快就遇到了問題。 有什么提示嗎?

這是你想要達到的目標嗎?

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

我想你正在尋找這樣的東西。

查找子列表的最小和最大大小。 然后創建一個字典,其鍵范圍從 min 到 max。

代碼:

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']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM