【问题标题】:Passing array range as argument to a function?将数组范围作为参数传递给函数?
【发布时间】:2015-04-23 13:09:45
【问题描述】:

有没有办法将数组范围作为参数传递给函数? 类似的东西:

> blah(ary,arg1=1:5)

def blah(ary,arg1): print ary[arg1]

【问题讨论】:

标签: python arrays numpy arguments


【解决方案1】:

Python 只接受方括号内的1:5 语法。解释器将其转换为slice 对象。然后对象的__getitem__ 方法应用切片。

查看numpy/lib/index_tricks.py 了解一些利用此功能的功能。实际上它们不是函数,而是定义了自己的__getitem__ 方法的类。该文件可能会给你一些想法。

但如果你没有做到这一点,那么可能性包括:

blah(arr, slice(1, 5))
blah(arr, np.r_[1:5])

nd_gridmgridogrid 扩展“切片”概念以接受虚构的“步长”值:

mgrid[-1:1:5j]
# array([-1. , -0.5,  0. ,  0.5,  1. ])

请注意,在将切片传递给您的 blah 函数之前,任何在切片上展开的内容都不会知道另一个参数的形状。所以np.r_[:-1] 只返回[]

None 可以用于slice:例如slice(None,None,-1) 等同于 [::-1]

【讨论】:

  • 如何检查我收到的参数是 slice() 还是普通数字?我知道了 isinstance(x,slice)
【解决方案2】:

你可以使用slice函数

>>> def blah(ary,arg1):
...     print ary[arg1]
>>> blah(range(10), slice(1, 5))
[1, 2, 3, 4]

【讨论】:

    【解决方案3】:

    你可以这样试试:

    def blah(ary, arg):
        arg = map(int, arg.split(":"))
        print ary[arg[0]:arg[1]]
    
    blah([1,2,3,4,5,6],"2:5")
    

    输出:

    [3, 4, 5]
    

    【讨论】:

      【解决方案4】:

      只是saw it happen today,我觉得这很奇怪,注意他们将参数test_idx作为普通范围

      plot_decision_regions(X=X_combined_std, y=y_combined,
                            classifier=ppn, test_idx=range(105, 150))
      

      那么这到底是做什么的呢?

      用它来分割一个 Numpy 数组

      ndarray[范围(105, 150), :]

      但是,当我通过复制 ndarray 值对其进行测试时,将其实例化并尝试自己对其进行切片(基本上是创建一个列表),它不允许我在看起来的切片上传递该范围。

      [[ 0.73088538 1.57698181], [ 0.17316034 0.1348488 ]]

      当您单击设置新值时,我从 ndarray 中提取/复制了它

      埃里克 = [[ 0.73088538 1.57698181], [ 0.17316034 0.1348488 ]]

      -- 语法错误。语法无效

      必须将逗号作为语法接受并将其实例化为列表 obj

      埃里克 = [[ 0.73088538, 1.57698181], [ 0.17316034, 0.1348488 ]]

      埃里克[:]

      (有效,返回整个东西)

      埃里克[范围(0, 1), :]

      -- 类型错误。列表索引必须是整数或切片,而不是元组

      (中断,我们之前测试过切片是有效的,所以它与范围有关)

      用自制的 Numpy Array 再试一次(剧透,它有效)

      erickNpa = np.asarray(erick, dtype=np.float32)
      erickNpa[range(0, 1), :]
      


      结论

      可以将范围作为参数传递,如第一部分所示,在某些时候代码没有执行,但必须这样做使用它正在做的事情的性质(使用它来切片列表),但是如果使用正确的脚手架,一切似乎都可以在使用 Numpy 数组时证明。



      示例代码

      我也会放 function def 以防 git 被删除,即使我链接了线路。

      def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
      
          # setup marker generator and color map
          markers = ('s', 'x', 'o', '^', 'v')
          colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
          cmap = ListedColormap(colors[:len(np.unique(y))])
      
          # plot the decision surface
          x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
          x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
          xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                                 np.arange(x2_min, x2_max, resolution))
          Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
          Z = Z.reshape(xx1.shape)
          plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
          plt.xlim(xx1.min(), xx1.max())
          plt.ylim(xx2.min(), xx2.max())
      
          for idx, cl in enumerate(np.unique(y)):
              plt.scatter(x=X[y == cl, 0], 
                          y=X[y == cl, 1],
                          alpha=0.8, 
                          c=colors[idx],
                          marker=markers[idx], 
                          label=cl, 
                          edgecolor='black')
      
          # highlight test examples
          if test_idx:
              # plot all examples
              X_test, y_test = X[test_idx, :], y[test_idx]
      
              plt.scatter(X_test[:, 0],
                          X_test[:, 1],
                          c='',
                          edgecolor='black',
                          alpha=1.0,
                          linewidth=1,
                          marker='o',
                          s=100, 
                          label='test set')
      
      
      # Training a perceptron model using the standardized training data:
      
      
      
      X_combined_std = np.vstack((X_train_std, X_test_std))
      y_combined = np.hstack((y_train, y_test))
      
      plot_decision_regions(X=X_combined_std, y=y_combined,
                            classifier=ppn, test_idx=range(105, 150))
      plt.xlabel('petal length [standardized]')
      plt.ylabel('petal width [standardized]')
      plt.legend(loc='upper left')
      
      plt.tight_layout()
      #plt.savefig('images/03_01.png', dpi=300)
      plt.show()
      

      【讨论】:

        猜你喜欢
        • 2012-12-07
        • 1970-01-01
        • 2013-01-27
        • 1970-01-01
        • 2017-08-17
        • 1970-01-01
        • 2018-06-26
        • 1970-01-01
        相关资源
        最近更新 更多