Python - 这是什么语法? my_2d_list [0:20,1]

时间:2014-10-08 23:34:15

标签: python brackets indices

在翻译或搜索翻译时遇到困难时间,以找出括号内的内容。这是上下文中的代码:

    from matplotlib.mlab import PCA as mlabPCA

    mlab_pca = mlabPCA(all_samples.T)

    print('PC axes in terms of the measurement axes'\
            ' scaled by the standard deviations:\n',\
              mlab_pca.Wt)

    plt.plot(mlab_pca.Y[0:20,0],mlab_pca.Y[0:20,1], 'o', markersize=7,\
            color='blue', alpha=0.5, label='class1')
    plt.plot(mlab_pca.Y[20:40,0], mlab_pca.Y[20:40,1], '^', markersize=7,\
            color='red', alpha=0.5, label='class2')

    plt.xlabel('x_values')
    plt.ylabel('y_values')
    plt.xlim([-4,4])
    plt.ylim([-4,4])
    plt.legend()
    plt.title('Transformed samples with class labels from matplotlib.mlab.PCA()')

    plt.show()

我尝试制作像

这样的小二维数组
    a = [[1,2],[1,2],[1,2],[1,2],[1,2]]

并评估

    a[0:2,0]

但这并没有给我任何东西。谢谢!

从“使用matplotlib.mlab库中的PCA()类”部分中的http://sebastianraschka.com/Articles/2014_pca_step_by_step.html获取的代码。

1 个答案:

答案 0 :(得分:2)

原生python列表(你为上面的a创建的内容)不支持索引或切片,至少就像你正在做的那样。未来有两种解决方案:

  1. 使用numpy
  2. 要访问索引和切片,您可以使用已经使用过的语法。

    import numpy as np
    a = np.array([[1,2],[1,2],[1,2],[1,2],[1,2]])
    a[0:2, 0] # returns array([1, 1])
    
    1. 使用不同的语法访问您的本机python列表。
    2. 请注意,此方法实际上不允许切片上面使用它的方式。但是,您可以执行:a[0][1]而不是a[0, 1],并使用列表正确访问0,1元素。但同样,没有切片(a[0:2][0]会产生一些不良结果)。

      好像你可能来自Matlab,只是基于一些句法选择。如果是这样,请使用这个出色的参考指南来简化过渡:http://wiki.scipy.org/NumPy_for_Matlab_Users