【问题标题】:Python - what is this syntax? my_2d_list[0:20,1]Python - 这是什么语法? my_2d_list[0:20,1]
【发布时间】:2014-10-08 23:34:14
【问题描述】:

很难用谷歌搜索或摆弄解释器来找出括号内的这个东西是什么。这是上下文中的代码:

    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

【问题讨论】:

    标签: python brackets indices


    【解决方案1】:

    本机 python 列表(您在上面为 a 创建的内容)不支持索引或切片,至少您的操作方式不支持。未来有两种解决方案:

    1. 使用 numpy

    要访问索引和切片,您可以使用已经在使用的语法。

    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 列表。

    请注意,此方法实际上不允许按照您在上面使用它的方式进行切片。但是,您可以这样做:a[0][1] 而不是 a[0, 1] 使用列表来正确访问 0、1 元素。但同样,没有切片(a[0:2][0] 会产生一些不希望的结果)。

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

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2015-12-04
    • 2014-03-31
    • 2015-09-24
    • 1970-01-01
    • 2010-12-13
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多