簡體   English   中英

在給定條件的情況下生成列表的所有組合

[英]Generate all combinations of a list given a condition

我想為k個變量列表生成長度為n的所有組合。 我可以這樣做:

import itertools
import pandas as pd
from sklearn import datasets

dataset = datasets.load_breast_cancer()
X = dataset.data
y = dataset.target
df = pd.DataFrame(X, columns=dataset.feature_names)
features = dataset.feature_names

x = set(['mean radius', 'mean texture'])

for s in itertools.combinations(features, 3):
    if x.issubset(set(s)):
        print s

len(特征)= 30,因此這將產生4060個組合,其中n = 3。 當n = 10時,這是30,045,015種組合。

len(tuple(itertools.combinations(features, 10)

然后將基於條件語句評估這些組合中的每一個。 然而,對於n> 10,這變得不可行。

而不是生成所有組合,然后按照本例中的某些條件進行過濾, 是否可以在此條件下生成所有組合?

換句話說,生成所有組合,其中n = 3,4,5 ... k,給定'平均半徑'和'平均紋理'出現在組合中?

只需生成沒有'mean radius''mean texture'組合,並將這兩個組合添加到每個組合中,從而大大減少了組合的數量。 這樣您就不必進行過濾,生成的每個組合都將非常有用。

# remove the fixed features from the pool:
features = set(features) - x 
for s in itertools.combinations(features, n - len(x)):
    s = set(s) & x # add the fixed features to each combination
    print(s)

暫無
暫無

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

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