简体   繁体   English

在给定条件的情况下生成列表的所有组合

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

I would like to generate all combinations of length n, for a list of k variables. 我想为k个变量列表生成长度为n的所有组合。 I can do this as follows: 我可以这样做:

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(features) = 30, thus this will generate 4060 combinations where n=3. len(特征)= 30,因此这将产生4060个组合,其中n = 3。 When n=10, this is 30,045,015 combinations. 当n = 10时,这是30,045,015种组合。

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

Each of these combinations will then be evaluated based on the conditional statement. 然后将基于条件语句评估这些组合中的每一个。 However for n>10 this becomes unfeasible. 然而,对于n> 10,这变得不可行。

Instead of generating all combinations, and then filtering by some condition like in this example, is it possible to generate all combinations given this condition? 而不是生成所有组合,然后按照本例中的某些条件进行过滤, 是否可以在此条件下生成所有组合?

In other words, generate all combinations where n=3, 4, 5 ... k, given 'mean radius' and 'mean texture' appear in the combination? 换句话说,生成所有组合,其中n = 3,4,5 ... k,给定'平均半径'和'平均纹理'出现在组合中?

Just generate the combinations without 'mean radius' and 'mean texture' and add those two to every combination, thus largely reducing the number of combinations. 只需生成没有'mean radius''mean texture'组合,并将这两个组合添加到每个组合中,从而大大减少了组合的数量。 This way you don't have to filter, every combination generated will be useful. 这样您就不必进行过滤,生成的每个组合都将非常有用。

# 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