Python 将值从函数追加到列表
我使用此功能:Python 将值从函数追加到列表,python,python-3.x,list,function,Python,Python 3.x,List,Function,我使用此功能: from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression X, y = load_iris(return_X_y=True) for i in range(X.shape[1]): clf = LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].resha
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
for i in range(X.shape[1]):
clf = LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].reshape(-1,1), y)
print(clf.score(X[:,i].reshape(-1,1),y))
我得到4个值作为输出:
0.7466666666666667
0.5533333333333333
0.9533333333333334
0.96
但当我尝试将这4个值添加到列表中时:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
for i in range(X.shape[1]):
my_list = []
clf = LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].reshape(-1,1), y)
my_list .append(clf.score(X[:,i].reshape(-1,1),y))
print(my_list)
我只得到最后一个值:
[0.96]
我想得到:
[0.7466666666666667, 0.5533333333333333, 0.9533333333333334, 0.96]
[0.7466666666666667, 0.5533333333333333, 0.9533333333333334, 0.96]
我该怎么做呢?确保在循环之外声明列表,这样它就不会被重置
my_list = []
for i in range(X.shape[1]):
# you were resetting the list each time
clf = LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].reshape(-1,1), y)
my_list .append(clf.score(X[:,i].reshape(-1,1),y))
您还可以使用列表理解来避免混淆:
my_list = [LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].reshape(-1,1), y).score(X[:,i].reshape(-1,1),y) for i in range(X.shape[1])]
两者都存储列表:
确保在循环之外声明列表,这样它就不会被重置
my_list = []
for i in range(X.shape[1]):
# you were resetting the list each time
clf = LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].reshape(-1,1), y)
my_list .append(clf.score(X[:,i].reshape(-1,1),y))
您还可以使用列表理解来避免混淆:
my_list = [LogisticRegression(random_state=0, verbose=0, max_iter=1000).fit(X[:,i].reshape(-1,1), y).score(X[:,i].reshape(-1,1),y) for i in range(X.shape[1])]
两者都存储列表: