将数组范围作为参数传递给函数?

Passing array range as argument to a function?

有没有办法将数组范围作为参数传递给函数? 像 :

> blah(ary,arg1=1:5)

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

你可以这样试试:

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]

您可以使用slice函数

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

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

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

但如果您不能做到这一点,则可能包括:

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

nd_gridmgridogrid 扩展 'slice' 概念以接受虚构的 'step' 值:

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

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

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

只是 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 ]]

which I extracted/copied from an ndarray when you click to set new value

erick = [[ 0.73088538 1.57698181], [ 0.17316034 0.1348488 ]]

-- 语法错误。语法无效

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

erick = [[ 0.73088538, 1.57698181], [ 0.17316034, 0.1348488 ]]

erick[:]

(有效,返回全部)

erick[range(0, 1), :]

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

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

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

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


结论

可以将范围作为参数传递,如在第一部分中所见,在某些时候代码是' t executing 但这与它正在做的事情的性质有关(使用它来分割列表),但是在正确的脚手架下,一切似乎都像使用 Numpy 数组时所证明的那样工作。



示例代码

我还会放置 函数 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()