给定条件生成列表的所有组合
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(features) = 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'出现在组合中?
只生成没有'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)
我想为一个包含 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(features) = 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'出现在组合中?
只生成没有'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)