在for循环中向后索引整个数组

问题描述:

假设我要遍历一个数组,并在循环索引内将数组的所有索引向前和向后移动,如下所示:

Suppose I would like to loop over an array and within the loop index the array forward and backward for all of its indices like so:

x = np.random.uniform(size=600)
for i in range(len(x)):
    dot = np.dot(x[:-i], x[i:])

现在这行不通,因为x[:-0]就像x[:0]一样,给出了[]. 我可以单独处理零号情况,但想知道是否还有更Python化的方法来做到这一点.

Now this doesn't work, because x[:-0] is just like x[:0] which gives []. I could handle the zero case separately but was wondering whether there's a more pythonic way of doing this.

使用切片值-i or None的结尾.如果i不为零,则它只是-i,但是如果它是0,则-0是虚假的,它求值并返回第二项None,这意味着运行到末尾".顺序".之所以可行,是因为foo[:None]等效于foo[:],当您省略切片的该部分时,它隐式变为None,但是显式地传递None也是完全合法的,

Use an end of slice value of -i or None. If i is non-zero, then it's just -i, but if it's 0, then -0 is falsy, and it evaluates and returns the second term, None, which means "run to end of sequence". This works because foo[:None] is equivalent to foo[:], when you omit that component of the slice it becomes None implicitly, but it's perfectly legal to pass None explicitly, with the same effect.

因此您的新行将是:

dot = np.dot(x[:-i or None], x[i:])