【问题标题】:Get sublists from list从列表中获取子列表
【发布时间】:2017-10-10 03:36:11
【问题描述】:

我正在尝试编写交叉验证代码,并且需要遍历一组并拆分训练和测试数据。我正在尝试按以下方式拆分它,但代码无法编译

import numpy as np
X = np.array([[1,2], [3,4], [5,6]])
n_folds = 3

for n in range(n_folds):
    test_fold = X[n]
    train_folds = X[x for x in range(n_folds) if x != n]
    print train_folds, test_fold

预期输出

[3,4,5,6], [1,2]
[1,2,5,6], [3,4]
[1,2,3,4], [5,6]

有什么方法可以实现吗?

【问题讨论】:

  • 在 1.6k+ rep 你应该知道你应该分享你得到的错误。

标签: python python-2.7 numpy


【解决方案1】:

添加额外的括号:

X[[x for x in range(n_folds) if x != n]]

内括号创建一个列表(理解),外括号告诉 numpy 使用该列表进行高级索引。

【讨论】:

    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 2019-05-25
    相关资源
    最近更新 更多