【发布时间】:2022-01-04 04:01:20
【问题描述】:
如何将每个循环生成的字典附加到列表中,以便最后我的函数返回一个 n 字典列表?没有任何花哨的库,只是普通的 python?
def inner_loop(*args):
for X, y in zip(X, y):
a_dict = {'t':None, 'p':None}
t_range = range(1, 10)
p_range = range('high','low')
best_acc = 0
list_of_dicts = []
#best grid selection
for t in t_range:
for p in p_range:
model(X, temp=t, press=p)
predict = model.prdeicting(y)
acc = (np.sum(predict == y))/len(y)
if acc > best_acc:
best_acc = acc
a_dict['t']= t
elif p == 'high':
a_dict.['p']='high'
elif p == 'low':
a_dict.['p']='low'
# I tried all options I knew here nothing really works:
list_of_dicts.append(a_dict)
list_of_dicts.append(a_dict.copy())
list_of_dicts.append(dict(a_dict))
return list_of_dicts
该函数返回一个字典实例,但从不返回所有已生成字典的附加列表。有人可以帮忙吗?
【问题讨论】:
-
你必须在外部
for循环开始之前放置list_of_dicts = []的声明,否则它只会继续覆盖列表而不是附加到它:/ -
感谢您的及时回复,这很有帮助,问题是该函数是
class的一部分,我不知道如何将声明放在函数之前。我必须在__init__函数中声明list_of_dicts = []吗?
标签: python list dictionary append