在下面的代码中,我声明三个列表只是为了查找三个变量的均值。代码可以更简洁吗?例如,使用一个列表。
import numpy as np
rmse_train_arr=[]
wt_error_train_arr=[]
rmse_test_arr=[]
for i in range(5):
rmse_train = i
wt_error_train=i+5
rmse_test=i+6
rmse_train_arr.append(rmse_train)
wt_error_train_arr.append(wt_error_train)
rmse_test_arr.append(rmse_test)
print(np.array(rmse_train_arr).mean(),np.array(wt_error_train_arr).mean(),np.array(rmse_test_arr).mean())
for i in range(5)
只是为了简化此处的目的,实际上,您可以假设您在for循环中不知道rmse_train
,wt_error_train
等的确切值。目的仅仅是在末尾找到自己的意思。
答案 0 :(得分:0)
认为这是保留列表的更好方法:
rmse_train_mean = 0
wt_error_train_mean = 0
rmse_test_mean = 0
counter = 0 # if you don't know how many elements there are
for i in range(5):
rmse_train = i
wt_error_train = i + 5
rmse_test = i + 6
rmse_train_mean += rmse_train
wt_error_train_mean += wt_error_train
rmse_test_mean += rmse_test
counter += 1
print(rmse_train_mean / counter, wt_error_train_mean / counter, rmse_test_mean / counter)
输出
2.0 7.0 8.0
至少有一种方法可以保留一个列表,但前提是必须这样:
import numpy as np
one = []
for i in range(5):
rmse_train = i
wt_error_train = i + 5
rmse_test = i + 6
one.extend([rmse_train, wt_error_train, rmse_test])
result = np.mean([one[::3], one[1::3], one[2::3]], axis=1)
输出
[2. 7. 8.]
第一种方法可以一次性完成所有操作,并且不会在内存中保留多个(或一个)列表。