在Python中将索引列表传递给另一个列表。正确语法?

4 投票
2 回答
12257 浏览
提问于 2025-04-18 18:05

我有以下来自sklearn的代码:

>>> from sklearn import cross_validation
>>> X = np.array([[1, 2], [3, 4], [1, 2], [3, 4]])
>>> y = np.array([1, 2, 3, 4])
>>> kf = cross_validation.KFold(4, n_folds=2)
>>> len(kf)
2
>>> print(kf)  
sklearn.cross_validation.KFold(n=4, n_folds=2, shuffle=False,
                           random_state=None)
>>> for train_index, test_index in kf:
...    print("TRAIN:", train_index, "TEST:", test_index)
...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]
TRAIN: [2 3] TEST: [0 1]
TRAIN: [0 1] TEST: [2 3]
.. automethod:: __init__

当我在这些代码行中传递train_index和test_index时,出现了一个错误(IndexError: indices are out-of-bounds):

...    X_train, X_test = X[train_index], X[test_index]
...    y_train, y_test = y[train_index], y[test_index]

为什么我不能把一个索引列表传给另一个列表?正确的语法是什么,才能把一个索引列表传给另一个列表,以获取那个列表中的元素?

我正在使用Python 2.7。

谢谢。

2 个回答

1

你也可以使用:

res_list = list(itemgetter(*index_list)(test_list)) 

补充说明:

这里有一个例子:

>>> import operator
>>> indices = [1, 3, 4]
>>> list(operator.itemgetter(*indices)(range(10)))
[1, 3, 4]
7

和Numpy数组不同,Python的列表不支持通过多个索引来访问。

不过,使用列表推导式可以很容易地解决这个问题:

l= range(10)
indexes= [1,3,5]
result= [l[i] for i in indexes]

或者使用稍微不那么容易读懂(但在某些情况下更有用)的map函数:

result= map(l.__getitem__, indexes)

不过,正如Ashwini Chaudhary所提到的,你的例子中的Xy实际上是Numpy数组,所以要么是你输入的示例代码有误,要么就是你的某些索引确实超出了范围。

撰写回答