Python:列表迭代只返回上一个值 [英] Python: list iteration only returns last value
问题描述
我正在使用scikit-learn进行GMM培训,并试图通过遍历整数列表来改变混合组件的数量。但是,当我打印我的结果模型时,我只能得到3个混合成分,或者我列出的最后一个项目。
这是我的代码:
from sklearn.mixture import GMM
$ b $ class_names = ['name1','name2','name3']
covs = ['spherical','diagonal','tied','full']
对于类名中的c,
模型[c] = dict((covar_type,GMM(n_components = num,
打印模型
covariance_type = covar_type,init_params ='wmc',n_init = 1,n_iter = 10))covs_type in covs for num in num_comp / pre>
有人可以帮忙吗?
非常感谢!
解决方案这是因为在表达式中:
$ (covar_type,GMM(n_components = num,
covariance_type = covar_type,init_params ='wmc',n_init = 1,n_iter = 10))for b $ b
dict covar_type in covs for num in num_comp)
您正在使用相同的 covar_type
作为所有迭代的关键字,从而重写相同的元素。
如果我们以更可读的方式编写代码,这就是发生的事情:
data = dict()
covs中的covar_type:
num_comp中的num:
#covar_type对于这个循环的所有迭代是相同的
#因此只有最后一个幸存
data [covar_type] = GMM(...)
如果您想保留所有值,您应该使用值列表而不是单个值或更改密钥。
e值列表:
data = dict()
covs中的covar_type:
data [covar_type ] = values = []
for num_comp:
values.append(GMM(...))
对于不同的键:
data = dict()
for covar_type in covs :
为num_comp中的num:
data [(covar_type,num)] = GMM(...)
I'm using scikit-learn for GMM training and am trying to vary the number of mixture components by looping over a list of integers. But when I print my resulting models I only get the ones with 3 mixture components, or whatever I put as the last item in my list.
This is my code:
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
Can someone help please?
Many thanks in advance!
解决方案 This happens because in the expression:
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)
You are using the same covar_type
as key over all iterations, thus rewriting the same element.
If we write the code in a more readable way, this is what it's happening:
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(...)
If you want to keep all the values you should use a list of values instead of a single value or change the key.
For the list of values:
data = dict()
for covar_type in covs:
data[covar_type] = values = []
for num in num_comp:
values.append(GMM(...))
For different keys:
data = dict()
for covar_type in covs:
for num in num_comp:
data[(covar_type, num)] = GMM(...)
这篇关于Python:列表迭代只返回上一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!