Python:列表迭代仅返回最后一个值

标签 python list for-loop scikit-learn

我正在使用 scikit-learn 进行 GMM 训练,并尝试通过循环整数列表来改变混合分量的数量。但是,当我打印生成的模型时,我只得到具有 3 个混合成分的模型,或者我在列表中作为最后一项放置的任何模型。

这是我的代码:

from sklearn.mixture import GMM

class_names = ['name1','name2','name3']
covs =  ['spherical', 'diagonal', 'tied', 'full']
num_comp = [1,2,3]

models = {}
for c in class_names:
    models[c] = dict((covar_type,GMM(n_components=num,
                covariance_type=covar_type, init_params='wmc',n_init=1, n_iter=10)) for covar_type in covs for num in num_comp)
print models

有人可以帮忙吗? 非常感谢!

最佳答案

发生这种情况是因为在表达式中:

dict((covar_type,GMM(n_components=num,
                covariance_type=covar_type, init_params='wmc',n_init=1, n_iter=10)) for covar_type in covs for num in num_comp)

您在所有迭代中使用相同的 covar_type 作为键,从而重写相同的元素。

如果我们以更具可读性的方式编写代码,就会发生这样的情况:

data = dict()
for covar_type in covs:
    for num in num_comp:
        # covar_type is the same for all iterations of this loop
        # hence only the last one "survives"
        data[covar_type] = GMM(...)

如果您想保留所有值,您应该使用值列表而不是单个值更改键。

对于值列表:

data = dict()
for covar_type in covs:
    data[covar_type] = values = []
    for num in num_comp:
        values.append(GMM(...))

对于不同的键:

data = dict()
for covar_type in covs:
    for num in num_comp:
        data[(covar_type, num)] = GMM(...)

关于Python:列表迭代仅返回最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20398242/

相关文章:

python - 将字符串作为参数传递会添加转义字符

python pandas到csv文件保存,而不是覆盖

python - Jupyter Notebook - 安装 python 2

使用范围而非容器的 Java JTwig For 循环

batch-file - 替换 FOR 循环中的子字符串

python - 正斜杠后面直接加句号的目的是什么?

python - 从文件加载大型数组,numpy 比列表追加慢。瓶颈在哪里?

performance - Python 3.3 在大循环期间变慢

Django-从模型中的所有对象获取第一个属性

r - 将数据帧列表转换为 R 中的单个数据帧