如何从循环中将多个词典附加到列表中,python?
How to append a multiple dictionaries to a list from a loop, python?
如何将每次循环生成的字典附加到一个列表中,以便在我的函数 returns 末尾添加一个包含 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
函数 returns 一个字典的实例,但从来不是生成的所有字典的附加列表。有人可以帮忙吗?
def func(*args):
list_of_dicts = []
for X, y in zip(X, y):
a_dict = make_your_a_dict() # what you do in your example
list_of_dicts.append(a_dict)
return list_of_dicts # check indentation level
也许有用。
如何将每次循环生成的字典附加到一个列表中,以便在我的函数 returns 末尾添加一个包含 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
函数 returns 一个字典的实例,但从来不是生成的所有字典的附加列表。有人可以帮忙吗?
def func(*args):
list_of_dicts = []
for X, y in zip(X, y):
a_dict = make_your_a_dict() # what you do in your example
list_of_dicts.append(a_dict)
return list_of_dicts # check indentation level
也许有用。